Vector intersection in C++

Tyler picture Tyler · Oct 21, 2013 · Viewed 46.2k times · Source

I have this function

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">

Answer

masoud picture masoud · Oct 21, 2013

Try std::set_intersection, for example:

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