C中的向量交集

新手上路,请多包涵

我有这个功能

vector<string> instersection(const vector<string> &v1, const vector<string> &v2);

我有两个字符串向量,我想找到两者中都存在的字符串,然后用公共元素填充第三个向量。

如果我的向量是…

 v1 = <"a","b","c">
v2 = <"b","c">

原文由 Tyler 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 692
1 个回答

试试 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 << ' ';
}

原文由 masoud 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏