C++中的矢量交集
Vector intersection in C++
本文关键字:C++ 更新时间:2023-10-16
我有这个函数
vector<string> instersection(const vector<string> &v1, const vector<string> &v2);
我有两个字符串向量,我想找到两个字符串中存在的字符串,然后用常见的枚举填充第三个向量。
如果我的矢量是...
v1 = <"a","b","c">
v2 = <"b","c">
尝试std::set_intersection
,例如:
#include <algorithm> //std::sort
#include <iostream> //std::cout
#include <string> //std::string
#include <vector> //std::vector
std::vector<std::string> intersection(std::vector<std::string> v1,
std::vector<std::string> v2){
std::vector<std::string> v3;
std::sort(v1.begin(), v1.end());
std::sort(v2.begin(), v2.end());
std::set_intersection(v1.begin(),v1.end(),
v2.begin(),v2.end(),
back_inserter(v3));
return v3;
}
int main(){
std::vector<std::string> v1 {"a","b","c"};
std::vector<std::string> v2 {"b","c"};
auto v3 = intersection(v1, v2);
for(std::string n : v3)
std::cout << n << ' ';
}
你只需要对较小的向量进行排序。然后对较大的向量进行单次传递,并使用二叉搜索测试其项目在较小向量中的存在。
与其排序,不如考虑通过从较小的向量中创建一个哈希集来交换内存,然后在较大的向量上循环检查这些元素,如此处所建议的那样。这将比排序和使用std::set_intersection
更快。
相关文章:
- 没有找到相关文章