C++ std::remove/std::remove_if/erase用法探讨
?std::remove 不會(huì)改變輸入vector/string的長度。其過程相當(dāng)于去除指定的字符,剩余字符往前靠。后面的和原始字符保持一致。?
需要注意的是,remove函數(shù)是通過覆蓋移去的,如果容器最后一個(gè)值剛好是需要?jiǎng)h除的,則它無法覆蓋掉容器中最后一個(gè)元素(具體可以看下圖執(zhí)行結(jié)果),相關(guān)測試代碼如下:
#include "stdafx.h" #include <iostream> #include <memory> #include <vector> #include <algorithm> #include <ctime>using namespace std;void ShowVec(const vector<int>& valList) {for (auto val : valList){cout << val << " ";}cout << endl; }bool IsOdd(int i) { return i & 1; }int main() {vector<int> c = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 8, 7, 6, 5, 4, 3, 2, 1};cout << "current v_size: " << c.size() << endl;ShowVec(c);remove(c.begin(), c.end(), 1);cout << "after remove, v_size: " << c.size() << endl;ShowVec(c);c.erase(std::remove(c.begin(), c.end(), 2), c.end());cout << "after erase remove 1, v_size: " << c.size() << endl;ShowVec(c);c.erase(std::remove_if(c.begin(), c.end(), IsOdd), c.end());cout << "after erase remove_if Odd, v_size: " << c.size() << endl;ShowVec(c);vector<int> vct;for (int i = 0; i < 1000000; i++){vct.push_back(i);}clock_t start_time = clock();/*for (vector<int>::iterator it = vct.begin(); it != vct.end();){if (IsOdd(*it)){it = vct.erase(it);}else{++it;}}*/vct.erase(std::remove_if(vct.begin(), vct.end(), IsOdd), vct.end());clock_t cost_time = clock() - start_time;std::cout << " 耗時(shí):" << cost_time << "ms" << std::endl;return 0; }執(zhí)行如下:
如果是注釋掉
vct.erase(std::remove_if(vct.begin(), vct.end(), IsOdd), vct.end());
采用erase直接刪除指定規(guī)則元素,需要注意的是,vector使用erase刪除元素,其返回值指向下一個(gè)元素,但是由于vector本身的性質(zhì)(存在一塊連續(xù)的內(nèi)存上),刪掉一個(gè)元素后,其后的元素都會(huì)向前移動(dòng),所以此時(shí)指向下一個(gè)元素的迭代器其實(shí)跟剛剛被刪除元素的迭代器是一樣的:
for (vector<int>::iterator it = vct.begin(); it != vct.end();){if (IsOdd(*it)){it = vct.erase(it);}else{++it;}}執(zhí)行結(jié)果如下:
由此可見,對大數(shù)據(jù)量的操作,用?vct.erase(std::remove_if(vct.begin(), vct.end(), IsOdd), vct.end()) 比直接用erase,效率提升非常大,算法整體復(fù)雜度低。
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的C++ std::remove/std::remove_if/erase用法探讨的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 教师节,收到学生的礼物和祝福,开心
- 下一篇: s3c2440移植MQTT