5

I have some vector<string> v1, which was filled using push_back:

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

I have some another vector<string> v2 and an iterator, which contains some element

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

And I need to check, is an v2iter element presents in v1, or not

find(v1, v2iter); //smth like this
radiolok
  • 53
  • 1
  • 7

2 Answers2

3

You can use standard algorithm std::find

For example

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

Or you can use standard algorithm std::any_of

For example

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

Or if the first vector is ordered then you can use algorithm std::binary_search

For example

#include <algorithm>
#include <vector>
//..
if ( std::binary_search( v1.begin(), v1.end(), *v2iter ) )
{
   std::cout << *v2iter << " is found in v1" << std::endl;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
1

You can find that using :

    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 
       }
    }
Amit Kumar
  • 1,477
  • 1
  • 16
  • 27