如何使用STL中的set_difference、set_intersection和set_union操作?
- 内容介绍
- 文章标签
- 相关推荐
本文共计336个文字,预计阅读时间需要2分钟。
以下是对原文的简化
以下是STL算法中的几个函数,它们适用于有序容器,如经过sort处理的vector和set。例如,set_difference用于找出第一个容器中有而第二个容器中没有的元素。
以下是STL algorithm的几个函数,使用的条件是有序容器,所以 vector在被sort了之后是可以使用的,set也是可以使用的。
set_difference 这个是求得在第一个容器中有,第二个容器中没有的。set_intersection 求两个容器的交, set_union 求两个容器的并。
set_symmetric_difference 求两个容器的差。
最后使用的时候注意要提前分配好最后的盛放容器,其大小最好是两个操作容器的和,然后需要根据返回的迭代器resize一下,看下面的例子。
// set_symmetric_difference example #include <iostream> // std::cout #include <algorithm> // std::set_symmetric_difference, std::sort #include <vector> // std::vector int main () { int first[] = {5,10,15,20,25}; int second[] = {50,40,30,20,10}; std::vector<int> v(10); // 0 0 0 0 0 0 0 0 0 0 std::vector<int>::iterator it; std::sort (first,first+5); // 5 10 15 20 25 std::sort (second,second+5); // 10 20 30 40 50 it=std::set_symmetric_difference (first, first+5, second, second+5, v.begin()); // 5 15 25 30 40 50 0 0 0 0 v.resize(it-v.begin()); // 5 15 25 30 40 50 std::cout << "The symmetric difference has " << (v.size()) << " elements:\n"; for (it=v.begin(); it!=v.end(); ++it) std::cout << ' ' << *it; std::cout << '\n'; return 0; }
本文共计336个文字,预计阅读时间需要2分钟。
以下是对原文的简化
以下是STL算法中的几个函数,它们适用于有序容器,如经过sort处理的vector和set。例如,set_difference用于找出第一个容器中有而第二个容器中没有的元素。
以下是STL algorithm的几个函数,使用的条件是有序容器,所以 vector在被sort了之后是可以使用的,set也是可以使用的。
set_difference 这个是求得在第一个容器中有,第二个容器中没有的。set_intersection 求两个容器的交, set_union 求两个容器的并。
set_symmetric_difference 求两个容器的差。
最后使用的时候注意要提前分配好最后的盛放容器,其大小最好是两个操作容器的和,然后需要根据返回的迭代器resize一下,看下面的例子。
// set_symmetric_difference example #include <iostream> // std::cout #include <algorithm> // std::set_symmetric_difference, std::sort #include <vector> // std::vector int main () { int first[] = {5,10,15,20,25}; int second[] = {50,40,30,20,10}; std::vector<int> v(10); // 0 0 0 0 0 0 0 0 0 0 std::vector<int>::iterator it; std::sort (first,first+5); // 5 10 15 20 25 std::sort (second,second+5); // 10 20 30 40 50 it=std::set_symmetric_difference (first, first+5, second, second+5, v.begin()); // 5 15 25 30 40 50 0 0 0 0 v.resize(it-v.begin()); // 5 15 25 30 40 50 std::cout << "The symmetric difference has " << (v.size()) << " elements:\n"; for (it=v.begin(); it!=v.end(); ++it) std::cout << ' ' << *it; std::cout << '\n'; return 0; }

