热查找<string>矢量<string>中的矢量元素

Hot to find vector<string> element in a vector<string>

本文关键字:string gt lt 元素 查找 矢量      更新时间:2023-10-16

我有一些vector<string> v1,使用push_back填充:

v1.push_back("a");
v1.push_back("b");
v1.push_back("c");
v1.push_back("d");
v1.push_back("e");

我有另一个vector<string> v2和一个迭代器,它包含某个元素

vector<string>::iterator v2iter;//some element of v2

我需要检查v1中是否有v2iter元素

find(v1, v2iter); //smth like this

可以使用标准算法std::find

例如

#include <algorithm>
#include <vector>
//..
if ( std::find( v1.begin(), v1.end(), *v2iter ) != v1.end() )
{
   std::cout << *v2iter << " is found in v1" << std::endl;
}

或者可以使用标准算法std::any_of

例如

#include <algorithm>
#include <vector>
#include <functional>
//..
if ( std::any_of( v1.begin(), v1.end(), std::bind2nd( std::equal_to<std::string>(), *v2iter ) ) )
{
   std::cout << *v2iter << " is found in v1" << std::endl;
}

或者如果第一个向量是有序的那么你可以使用算法std::binary_search

例如

#include <algorithm>
#include <vector>
//..
if ( std::binary_search( v1.begin(), v1.end(), *v2iter ) )
{
   std::cout << *v2iter << " is found in v1" << std::endl;
}

您可以使用:

    vector <string > :: iterator it , fit ;
    for ( it = v2.begin() ; it != v2.end() ; it++ ){
       fit = find ( v1.begin() , v1.end() , *it ) ;
       if ( fit != v1.end() ){
        // means that the element is present in v1 
       }
    }