2017-03-02 3 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)

현재 I이 방법은 다음

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를 사용하여

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

출력 :

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

어느 하나가 당신이 뭘 하려는지에 따라 일을 할 수있다 (위의 예는 기준에서 직접이다).