矢量交集在C + + [英] Vector intersection in C++
本文介绍了矢量交集在C + +的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个功能
vector<string> instersection(const vector<string> &v1, const vector<string> &v2);
我有两个字符串向量,我想找到两个字符串,然后用公共元素填充第三向量。
I have two vectors of strings and I want to find the strings that are present in both, which then fills a third vector with the common elemnts.
如果我的向量是...
If my vectors are...
v1 = <"a","b","c">
v2 = <"b","c">
推荐答案
尝试 std :: set_intersection
,例如:
Try std::set_intersection
, for example:
vector<string> instersection(vector<string> &v1, vector<string> &v2)
{
vector<string> v3;
sort(v1.begin(), v1.end());
sort(v2.begin(), v2.end());
set_intersection(v1.begin(),v1.end(),v2.begin(),v2.end(),back_inserter(v3));
return v3;
}
int main()
{
std::vector<string> v1 {"a","b","c"};
std::vector<string> v2 {"b","c"};
auto v3 = instersection(v1, v2);
for(string n : v3)
std::cout << n << ' ';
}
这篇关于矢量交集在C + +的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文