bool IsOdd (int i) { return ((i%2)==1); }
int main () {
int myints[] = {1,2,3,4,5,6,7,8,9}; // 1 2 3 4 5 6 7 8 9
// bounds of range:
int* pbegin = myints; // ^
int* pend = myints+sizeof(myints)/sizeof(int); // ^ ^
pend = std::remove_if (pbegin, pend, IsOdd); // 2 4 6 8
// ^ ^
std::cout << the range contains:;
for (int* p=pbegin; p!=pend; ++p)
std::cout << ' ' << *p;
std::cout << ' ';
return 0;
}
输出:
|
|
the range contains: 2 4 6 8 |
remove_copy
拷贝一个范围的元素,将其中值等价于给定值的元素删除
|
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
// remove_copy example #include #include #include int main () { int myints[] = {10,20,30,30,20,10,10,20}; // 10 20 30 30 20 10 10 20 std::vector std::remove_copy (myints,myints+8,myvector.begin(),20); // 10 30 30 10 10 0 0 0 std::cout << myvector contains:; for (std::vector std::cout << ' ' << *it; std::cout << ' '; return 0; } |
输出:
|
|
myvector contains: 10 30 30 10 10 0 0 0 |
remove_copy_if
拷贝一个范围的元素,将其中值满足给定条件的元素删除
|
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
// remove_copy_if example #include #include #include bool IsOdd (int i) { return ((i%2)==1); } int main () { int myints[] = {1,2,3,4,5,6,7,8,9}; std::vector std::remove_copy_if (myints,myints+9,myvector.begin(),IsOdd); std::cout << myvector contains:; for (std::vector std::cout << ' ' << *it; std::cout << ' '; return 0; } |
输出:
|
|
myvector contains: 2 4 6 8 0 0 0 0 0 |
replace
将一个范围中值等价于给定值的元素赋值为新的值
|
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
// replace algorithm example #include #include #include int main () { int myints[] = { 10, 20, 30, 30, 20, 10, 10, 20 }; std::vector std::replace (myvector.begin(), myvector.end(), 20, 99); // 10 99 30 30 99 10 10 99 std::cout << myvector contains:; for (std::vector std::cout << ' ' << *it; std::cout << ' '; return 0; } |
输出:
|
|
myvector contains: 10 99 30 30 99 10 10 99 |
replace_copy
拷贝一个范围的元素,将其中值等价于给定值的元素赋值为新的值
|
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
// replace_copy example #include #include #include int main () { int myints[] = { 10, 20, 30, 30, 20, 10, 10, 20 }; std::vector std::replace_copy (myints, myints+8, myvector.begin(), 20, 99); std::cout << myvector contains:; for (std::vector std::cout << ' ' << *it; std::cout << ' '; return 0; } |
输出:
|
|
myvector contains: 10 99 30 30 99 10 10 99 |
replace_copy_if
拷贝一个范围的元素,将其中值满足给定条件的元素删除
|
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
// replace_copy_if example #include #include #include bool IsOdd (int i) { return ((i%2)==1); } int main () { std::vector // set some values: for (int i=1; i<10; i++) foo.push_back(i); // 1 2 3 4 5 6 7 8 9 bar.resize(foo.size()); // allocate space std::replace_copy_if (foo.begin(), foo.end(), bar.begin(), IsOdd, 0); // 0 2 0 4 0 6 0 8 0 std::cout << bar contains:; for (std::vector std::cout << ' ' << *it; std::cout << ' '; return 0; } |
输出:
|
|
s |