建设银行e路通网网站,微信安装,wordpress无法上传,wordpress收费么std::remove 不会改变输入vector/string的长度。其过程相当于去除指定的字符#xff0c;剩余字符往前靠。后面的和原始字符保持一致。
需要注意的是#xff0c;remove函数是通过覆盖移去的#xff0c;如果容器最后一个值刚好是需要删除的#xff0c;则它无法覆盖掉容器…std::remove 不会改变输入vector/string的长度。其过程相当于去除指定的字符剩余字符往前靠。后面的和原始字符保持一致。
需要注意的是remove函数是通过覆盖移去的如果容器最后一个值刚好是需要删除的则它无法覆盖掉容器中最后一个元素具体可以看下图执行结果相关测试代码如下
#include stdafx.h
#include iostream
#include memory
#include vector
#include algorithm
#include ctimeusing namespace std;void ShowVec(const vectorint valList)
{for (auto val : valList){cout val ;}cout endl;
}bool IsOdd(int i) { return i 1; }int main()
{vectorint 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);vectorint vct;for (int i 0; i 1000000; i){vct.push_back(i);}clock_t start_time clock();/*for (vectorint::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 耗时 cost_time ms std::endl;return 0;
}
执行如下 如果是注释掉
vct.erase(std::remove_if(vct.begin(), vct.end(), IsOdd), vct.end());
采用erase直接删除指定规则元素需要注意的是vector使用erase删除元素其返回值指向下一个元素但是由于vector本身的性质存在一块连续的内存上删掉一个元素后其后的元素都会向前移动所以此时指向下一个元素的迭代器其实跟刚刚被删除元素的迭代器是一样的
for (vectorint::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()) 比直接用erase效率提升非常大算法整体复杂度低。