//分区拷贝
/*
* @ partition_copy
* @ 按照谓词讲源集合中满足条件的元素拷贝到第一个集合,不满足的拷贝到第二个集合
*/
vector<int> src = { 15,32,36,19,21,85,66 };
vector<int> des1, des2;
des2.resize(src.size());
des1.resize(src.size());
auto res = partition_copy(cbegin(src), cend(src), begin(des1), begin(des2),
[](int i) {return i % 2 == 0; });
des1.erase(res.first, end(des1));
des2.erase(res.second, end(des2));
//偶数集合(条件为真放在第一个里面)
cout << "偶数:";
for (auto i : des1) {
cout << i << "\t";
}
cout << endl;
//奇数集合(条件为假)
cout << "基数:";
for (auto i : des2) {
cout << i <<"\t";
}
cout << endl;
/* @ 分区算法,
* @ partition
* @ 按照给定谓词讲集合中满足条件的元素放到集合前面,不满足的放在集合尾部
*/
partition(begin(src), end(src),
[](int i) {return i % 2 == 0; });
//偶数在前,奇数在后
for (auto i : src)
{
cout << i << "\t";
}
cout << endl;
//集合算法
/*
* @ 并集 set_union() 得到两个集合中的所有元素
* @ 交集 set_intersection() 得到同时存在两个集合的元素
* @ 补集 set_difference() 存在第一个集合但不存在第二个集合
* @ 异或 set_symmetric_difference() 存在于某一个集合但是不同时存在于两个集合的元素
* @ 注: 使用集合函数前,集合必须是有序集合
*/
vector<int> vec1 = { 15,20,35,48,95,62 }, vec2 = {3,5,35,48,95,102}, result;
sort(vec1.begin(), vec1.end());
sort(vec2.begin(), vec2.end());
//并集
result.resize(vec1.size() + vec2.size());
auto newEnd = set_union(cbegin(vec1), cend(vec1), cbegin(vec2), cend(vec2), begin(result));
for_each(result.begin(), newEnd,
[](int i) {cout << i << " "; });
cout << endl;
//并集
result.resize(vec1.size() + vec2.size());
newEnd = set_intersection(cbegin(vec1), cend(vec1), cbegin(vec2), cend(vec2), begin(result));
for_each(result.begin(), newEnd,
[](int i) {cout << i << " "; });
cout << endl;
//补集
result.resize(vec1.size() + vec2.size());
newEnd = set_difference(cbegin(vec1), cend(vec1), cbegin(vec2), cend(vec2), begin(result));
for_each(result.begin(), newEnd,
[](int i) {cout << i << " "; });
cout << endl;
result.resize(vec1.size() + vec2.size());
newEnd = set_symmetric_difference(cbegin(vec1), cend(vec1), cbegin(vec2), cend(vec2), begin(result));
for_each(result.begin(), newEnd,
[](int i) {cout << i << " "; });
cout << endl;
STL算法 - 分区与集合算法
最新推荐文章于 2022-09-25 10:34:56 发布