Compare two vectors C++

后端 未结 4 1152
忘掉有多难
忘掉有多难 2020-12-13 20:37

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 it

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-13 21:08

    std::sort(v1.begin(), v1.end());
    std::sort(v2.begin(), v2.end());
    std::vector 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 s1(v1.begin(), v1.end());
    std::set s2(v2.begin(), v2.end());
    std::vector v3;
    std::set_intersection(s1.begin(), s1.end(), s2.begin(), s2.end(), std::back_inserter(v3));
    

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

提交回复
热议问题