比较两个向量C ++ [英] Compare two vectors C++

查看:159
本文介绍了比较两个向量C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道有没有任何函数比较2字符串向量返回不同(或相同)元素的数量?或者我必须遍历它们,并逐项测试。

谢谢。

I was wondering is there any function to compare 2 string vectors to return the number of different(or the same) elements? Or i have to iterate over both of them and test item by item.
Thanks.

推荐答案

std::sort(v1.begin(), v1.end());
std::sort(v2.begin(), v2.end());
std::vector<string> v3;
std::set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(), std::back_inserter(v3));

或者,如果您不想排序:

Or, if you don't want to sort:

std::set<string> s1(v1.begin(), v1.end());
std::set<string> s2(v2.begin(), v2.end());
std::vector<string> v3;
std::set_intersection(s1.begin(), s1.end(), s2.begin(), s2.end(), std::back_inserter(v3));

如果向量中可能存在重复项,可以使用multiset。

You may want to use a multiset if there could be duplicates in a vector.

这篇关于比较两个向量C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆