shuffle (foo.begin(), foo.end(), std::default_random_engine(seed));
std::cout << shuffled elements:;
for (int& x: foo) std::cout << ' ' << x;
std::cout << ' ';
return 0;
}
输出:
|
|
shuffled elements: 3 1 4 2 5 |
swap
交换两个对象的值
|
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
// swap algorithm example (C++98) #include #include #include int main () { int x=10, y=20; // x:10 y:20 std::swap(x,y); // x:20 y:10 std::vector std::swap(foo,bar); // foo:6x10 bar:4x20 std::cout << foo contains:; for (std::vector std::cout << ' ' << *it; std::cout << ' '; return 0; } |
输出:
|
|
foo contains: 10 10 10 10 10 10 |
swap_ranges
交换两个范围的元素
|
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
// swap_ranges example #include #include #include int main () { std::vector std::vector std::swap_ranges(foo.begin()+1, foo.end()-1, bar.begin()); // print out results of swap: std::cout << foo contains:; for (std::vector std::cout << ' ' << *it; std::cout << ' '; std::cout << bar contains:; for (std::vector std::cout << ' ' << *it; std::cout << ' '; return 0; } |
输出:
|
2 |
foo contains: 10 33 33 33 10 bar contains: 10 10 10 33 33 |
transform
对指定范围中的每个元素调用某个函数以改变元素的值
|
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
// transform algorithm example #include #include #include #include int op_increase (int i) { return ++i; } int main () { std::vector std::vector // set some values: for (int i=1; i<6; i++) foo.push_back (i*10); // foo: 10 20 30 40 50 bar.resize(foo.size()); // allocate space std::transform (foo.begin(), foo.end(), bar.begin(), op_increase); // bar: 11 21 31 41 51 // std::plus adds together its two arguments: std::transform (foo.begin(), foo.end(), bar.begin(), foo.begin(), std::plus // foo: 21 41 61 81 101 std::cout << foo contains:; for (std::vector std::cout << ' ' << *it; std::cout << ' '; return 0; } |
输出:
|
|
foo contains: 21 41 61 81 101 |
unique
删除指定范围中的所有连续重复元素,仅仅留下每组等值元素中的第一个元素
|
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
// unique algorithm example #include #include #include bool myfunction (int i, int j) { return (i==j); } int main () { int myints[] = {10,20,20,20,30,30,20,20,10}; // 10 20 20 20 30 30 20 20 10 std::vector // using default comparison: std::vector it = std::unique (myvector.begin(), myvector.end()); // 10 20 30 20 10 // ^ myvector.resize( std::distance(myvector.begin(),it) ); // 10 20 30 20 10 // using predicate comparison: std::unique (myvector.begin(), myvector.end(), myfunction); // (no changes) // print out content: std::cout << myvector contains:; for (it=myvector.begin(); it!=myvector.end(); ++it) std::cout << ' ' << *it; std::cout << ' '; return 0; } |
输出:
|
|
myvector contains: 10 20 30 20 10 |
unique_copy
拷贝指定范围的唯一化(参考上述的 unique)结果
|
2 3 4 5 6 7 8 9 10 11 |