我想计算两个向量之间的并集:
std::vector<pair<string,string>> p1;
std::vector<pair<string,string>> p2;
问题是为什么联合是在第二个元素而不是第一个元素上完成的?union 的大小应该等于4。是否可以修改 set_union 以便在第一个元素上完成联合?
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
std::vector<pair<string,string>> p1;
std::vector<pair<string,string>> p2;
p1.push_back(make_pair("A","1"));
p1.push_back(make_pair("B","2"));
p1.push_back(make_pair("C","3"));;
p2.push_back(make_pair("A","4"));
p2.push_back(make_pair("B","5"));
p2.push_back(make_pair("C","6"));
p2.push_back(make_pair("D","7"));
//sort vectors according to first element
sort(p1.begin(), p1.end(), [](const pair<string,string>& lhs, const pair<string,string>& rhs) {return lhs.first < rhs.first; });
sort(p2.begin(), p2.end(), [](const pair<string,string>& lhs, const pair<string,string>& rhs) {return lhs.first < rhs.first; });
//initialize vectors
std::vector<pair<string,string>> v(p1.size() + p2.size());
std::vector<pair<string,string>>::iterator it;
//compute union
it=std::set_union(p1.begin(), p1.end(),p2.begin(), p2.end(), v.begin());
v.resize(it-v.begin());
//print size
//size = 4
cout << v.size() << endl;
return 0;
}