25

私はこの機能を持っています

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

文字列の 2 つのベクトルがあり、両方に存在する文字列を見つけたいと考えています。次に、3 番目のベクトルを共通の要素で埋めます。

私のベクトルが...

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

3 に答える 3

52

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 << ' ';
}
于 2013-10-20T22:43:13.700 に答える
6

小さい方のベクトルだけをソートする必要があります。次に、より大きなベクトルに対して 1 回のパスを実行し、二分探索を使用して、より小さなベクトルでその項目の存在をテストします。

于 2016-02-03T19:32:42.307 に答える