remove(b,e,v) //[b,e) 删value
remove_if(b,e,p) //[b,e) 删p条件
remove_copy(b,e,r,v) //[b,e) 删v,结果存入r
remove_copy_if(b,e,r,p) //[b,e) 删p条件,结果存入r
remove和remove_if结果相同,只是传入的条件不一样。示例图如下:
remove_copy和remove_copy_if会把pass的元素保存在目标迭代器,而不是直接在原始数据上修改。
#include <iostream>
#include <string>
#include<vector>
#include <algorithm>
using namespace std;
template<typename T>
void Print(T& v) {
typename T::iterator iter = v.begin();
while (iter != v.end()) {
cout << *iter++ << " ";
}
cout << endl;
}
bool condition(int x) {
return x == 2;
}
int main() {
cout << "测试remove" << endl;
int data[] = {1,3,2,3,2,1,3,2};
vector<int> vec(data, data + 8);
vector<int>::iterator ivec, it;
ivec = remove(vec.begin(), vec.end(), 2);
for (it = vec.begin(); it != ivec; it++) {
cout << *it << " ";
} //打印1 3 3 1 3
cout << endl;
cout << "实际数据是" << endl;
Print(vec); //打印1 3 3 1 3 1 3 2
cout << endl;
cout << "测试remove_if" << endl;
int data3[] = { 1,3,2,3,2,1,3,2 };
vector<int> vec3(data3, data3 + 8);
vector<int>::iterator ivec3, it3;
ivec3 = remove_if(vec3.begin(), vec3.end(), condition);
for (it3 = vec3.begin(); it3 != ivec3; it3++) {
cout << *it3 << " ";
}//打印1 3 3 1 3
cout << endl;
cout << "实际数据是" << endl;
Print(vec3);//打印1 3 3 1 3 1 3 2
cout << endl;
cout << "测试remove_copy" << endl;
int data2[] = { 1,3,2,3,2,1,3,2 };
vector<int> vec2(data2, data2 + 8);
vector<int>::iterator ivec2, it2;
vector<int> myvec2(8);
ivec2 = remove_copy(vec2.begin(), vec2.end(), myvec2.begin(), 2);
for (it2 = vec2.begin(); it2 != ivec2; it2++) {
cout << *it2 << " ";
}//打印1 3 3 1 3
cout << endl;
cout << "实际数据是" << endl;
Print(vec2);//打印1 3 2 3 2 1 3 2
cout << endl;
cout << "测试remove_copy_if" << endl;
int data4[] = { 1,3,2,3,2,1,3,2 };
vector<int> vec4(data4, data4 + 8);
vector<int>::iterator ivec4, it4;
ivec4 = remove_copy_if(vec4.begin(), vec4.end(), vec4.begin(), condition);
for (it4 = vec4.begin(); it4 != ivec4; it4++) {
cout << *it4 << " ";
}
cout << endl;//打印1 3 3 1 3
cout << "实际数据是" << endl;
Print(vec4);//打印1 3 2 3 2 1 3 2
return 0;
}