中的“集合”set_intersection
并不意味着std::set
——它只是意味着一个逻辑集合;一组东西。如果两个集合都已排序,您可以简单地set_intersection
将两个集合放入第三个容器中。
vector<int> common;
set_intersection(v.begin(), v.end(), s.begin(), s.end(), back_inserter(common));
编辑:
这是一个完整的示例,说明了上述内容。这使用 C++11 lambdas,但如果您没有 C++11 或不能使用 lambdas,您可以使用仿函数代替它们。请注意缺少显式循环。
#include <set>
#include <vector>
#include <algorithm>
#include <iterator>
#include <functional>
#include <iostream>
using namespace std;
static const int numbers[] = {0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181};
static const size_t num_numbers = sizeof(numbers)/sizeof(numbers[0]);
int main()
{
/*** GET THE SET ****/
set<int> s(begin(numbers), end(numbers));
//copy(&numbers[0], &numbers[num_numbers], inserter(s, s.begin()));
/*** GET THE NUMBERS TO LOOK FOR **/
int first = 5, last = 10;
vector<int> targets;
generate_n(back_inserter(targets), last-first, [&first]() -> int {
return first++;
});
/*** FIND THE INTERSECTION ***/
vector<int> common;
set_intersection(s.begin(), s.end(), targets.begin(), targets.end(), back_inserter(common));
/*** DUMP RESULTS ***/
cout << "Intersecton of:\n\t";
copy(s.begin(), s.end(), ostream_iterator<int>(cout,"\t"));
cout << "\nwith:\n\t";
copy(targets.begin(), targets.end(), ostream_iterator<int>(cout,"\t"));
cout << "\n= = = = = = = =\n\t";
copy(common.begin(), common.end(), ostream_iterator<int>(cout,"\t"));
cout << "\n";
}
输出是:
Intersecton of:
0 1 2 3 5 8 13 21 34
55 89 144 233 377 610 987 1597 2584 4181
with:
5 6 7 8 9
= = = = = = = =
5 8