std::remove 不会改变输入vector/string的长度。其过程相当于去除指定的字符,剩余字符往前靠。后面的和原始字符保持一致。

需要注意的是,remove函数是通过覆盖移去的,如果容器最后一个值刚好是需要删除的,则它无法覆盖掉容器中最后一个元素(具体可以看下图执行结果),相关测试代码如下:

#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 << " 耗时:" << cost_time << "ms" << std::endl;

return 0;
}

执行如下:

C++之std::remove/std::remove_if/erase用法探讨_C++ 11

如果是注释掉

vct.erase(std::remove_if(vct.begin(), vct.end(), IsOdd), vct.end());

采用erase直接删除指定规则元素,需要注意的是,vector使用erase删除元素,其返回值指向下一个元素,但是由于vector本身的性质(存在一块连续的内存上),删掉一个元素后,其后的元素都会向前移动,所以此时指向下一个元素的迭代器其实跟刚刚被删除元素的迭代器是一样的:

for (vector<int>::iterator it = vct.begin(); it != vct.end();)
{
if (IsOdd(*it))
{
it = vct.erase(it);
}
else
{
++it;
}
}

执行结果如下:

C++之std::remove/std::remove_if/erase用法探讨_C++_02

由此可见,对大数据量的操作,用 vct.erase(std::remove_if(vct.begin(), vct.end(), IsOdd), vct.end()) 比直接用erase,效率提升非常大,算法整体复杂度低。