STL 集合部分操作
阿新 • • 發佈:2018-03-27
stl 標準 include algorithm begin LG -s def 構造
set_intersection
default (1) |
template <class InputIterator1, class InputIterator2, class OutputIterator> OutputIterator set_intersection (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result); |
---|---|
custom (2) |
template <class InputIterator1, class InputIterator2, class OutputIterator, class Compare> OutputIterator set_intersection (InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result, Compare comp); |
求兩個(已排序)集合的交集。
構造一個排序的範圍,從result的位置開始,然後是兩個排序範圍的集合的交集[first1,last1]和[first2,last2)。
兩個集合的交集只由兩個集合中的元素組成。由函數復制的元素總是以相同的順序從第一個範圍開始。
默認升序排列,也可以用comp自定義。兩個元素,a和b被認為是相等的,如果(!(a<b) && !(b<a)或if (!comp(a,b) && !comp(b,a))。
範圍內的元素已經按照相同的標準(操作符<或comp)排序。結果的範圍也根據這個排序。
1. 前四個參數,可以是叠代器(vector,set)的首尾,也可以是數組的首尾,只要是有序的區間均可註意區間均為左閉右開。
2. 第五個參數,可以是vector(註意一定要預留大小!用it取得set_intersection的返回值後再resize),也可以是數組。
3. compare函數自己編寫
1 // set_intersection example 2 #include <iostream> // std::cout 3 #include <algorithm> // std::set_intersection, std::sort 4 #include <vector> // std::vector 5 6 int main () { 7 int first[] = {5,10,15,20,25}; 8 int second[] = {50,40,30,20,10}; 9 std::vector<int> v(10); // 0 0 0 0 0 0 0 0 0 0 10 std::vector<int>::iterator it; 11 12 std::sort (first,first+5); // 5 10 15 20 25 13 std::sort (second,second+5); // 10 20 30 40 50 14 15 it=std::set_intersection (first, first+5, second, second+5, v.begin()); 16 // 10 20 0 0 0 0 0 0 0 0 17 v.resize(it-v.begin()); // 10 20 18 19 std::cout << "The intersection has " << (v.size()) << " elements:\n"; 20 for (it=v.begin(); it!=v.end(); ++it) 21 std::cout << ‘ ‘ << *it; 22 std::cout << ‘\n‘; 23 24 return 0; 25 }
set_union
求並集,方法和註意點與上面相同
set_difference
求差集,同上
merge
1 // merge algorithm example 2 #include <iostream> // std::cout 3 #include <algorithm> // std::merge, std::sort 4 #include <vector> // std::vector 5 6 int main () { 7 int first[] = {5,10,15,20,25}; 8 int second[] = {50,40,30,20,10}; 9 std::vector<int> v(10); 10 11 std::sort (first,first+5); 12 std::sort (second,second+5); 13 std::merge (first,first+5,second,second+5,v.begin()); 14 15 std::cout << "The resulting vector contains:"; 16 for (std::vector<int>::iterator it=v.begin(); it!=v.end(); ++it) 17 std::cout << ‘ ‘ << *it; 18 std::cout << ‘\n‘; 19 20 return 0; 21 }
合並兩個有序區間
STL 集合部分操作