C++中的矢量交集

Tyl*_*ler 20 c++ intersection vector

我有这个功能

vector<string> instersection(const vector<string> &v1, const vector<string> &v2);
Run Code Online (Sandbox Code Playgroud)

我有两个字符串向量,我想找到两者中存在的字符串,然后用常见的元素填充第三个向量.

如果我的载体是...

v1 = <"a","b","c">
v2 = <"b","c">
Run Code Online (Sandbox Code Playgroud)

mas*_*oud 42

试试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 << ' ';
}
Run Code Online (Sandbox Code Playgroud)

  • 这使`v1`和`v2`突变,OP具有const vector &lt;string&gt;&`。在这里按价值取值可能更可取 (2认同)

小智 5

您只需要对较小的向量进行排序。然后对较大的向量进行一次遍历,并通过使用二分搜索来测试较小向量中其项的存在。