2017-03-02 4 views
1

ベクトルv1がベクトルv2の内側にあるかどうかを調べようとしています。別のベクトルの中のベクトルを検索する

たとえば、v1 =(b、a)、v2 =(g、e、f、a、b)の場合。私はv2のbとaの両方をチェックする必要があります。

次のコードは、注文が同じ場合にのみ役立ちます。

std::search(v2.begin(), v2.end(), v1.begin(), v1.end()); 

すなわち、V2 =(G、E、F、B、A)

現在、私は次のよう

for (std::vector<std::string>::iterator it = v1.begin(); it != v1.end(); ++it) 
{ 
    if (std::find(v2.begin(), v2.end(), *it) != v2.end()) 
     std::cout << "found\n"; 
    else 
     std::cout << "not found\n"; 
} 

を通じて実現していますが、上記を使用して達成する方法がある場合std :: searchを使って?

答えて

3

あなたはstd::set_intersectionを使用することができます。

#include <iostream> 
#include <vector> 
#include <algorithm> 
#include <iterator> 
int main() 
{ 
    std::vector<char> v1{'a','b','e','f','g'}; 
    std::vector<char> v2{'a','b'}; 
    std::sort(v1.begin(), v1.end()); 
    std::sort(v2.begin(), v2.end()); 

    std::vector<char> v_intersection; 

    std::set_intersection(v1.begin(), v1.end(), 
          v2.begin(), v2.end(), 
          std::back_inserter(v_intersection)); 
    for(int n : v_intersection) 
     std::cout << n << ' '; 
} 

See the reference

operator<を使用して比較する要素に依存しているため、二つのベクトルが前std::set_intersectionを使用して、同じソート機能を使用してソートされている必要があることに注意してくださいstd::includes

#include <iostream> 
#include <algorithm> 
#include <cctype> 
#include <vector> 

int main() 
{ 
    std::vector<char> v1 {'a', 'b', 'c', 'f', 'h', 'x'}; 
    std::vector<char> v2 {'a', 'b', 'c'}; 
    std::vector<char> v3 {'a', 'c'}; 
    std::vector<char> v4 {'g'}; 
    std::vector<char> v5 {'a', 'c', 'g'}; 

    for (auto i : v1) std::cout << i << ' '; 
    std::cout << "\nincludes:\n" << std::boolalpha; 

    for (auto i : v2) std::cout << i << ' '; 
    std::cout << ": " << std::includes(v1.begin(), v1.end(), v2.begin(), v2.end()) << '\n'; 
    for (auto i : v3) std::cout << i << ' '; 
    std::cout << ": " << std::includes(v1.begin(), v1.end(), v3.begin(), v3.end()) << '\n'; 
    for (auto i : v4) std::cout << i << ' '; 
    std::cout << ": " << std::includes(v1.begin(), v1.end(), v4.begin(), v4.end()) << '\n'; 
    for (auto i : v5) std::cout << i << ' '; 
    std::cout << ": " << std::includes(v1.begin(), v1.end(), v5.begin(), v5.end()) << '\n'; 

    auto cmp_nocase = [](char a, char b) { 
    return std::tolower(a) < std::tolower(b); 
    }; 

    std::vector<char> v6 {'A', 'B', 'C'}; 
    for (auto i : v6) std::cout << i << ' '; 
    std::cout << ": (case-insensitive) " 
      << std::includes(v1.begin(), v1.end(), v6.begin(), v6.end(), cmp_nocase) 
      << '\n'; 
} 

OUTPUT:

a b c f h x 
includes: 
a b c : true 
a c : true 
g : false 
a c g : false 
A B C : (case-insensitive) true 

Here is the reference page

いずれかが、あなたがやろうとしているものに応じて仕事をすることができます(上記の例では、参照からの直接です)。

関連する問題