Home > other >  how to use find_if to find element in given vector of pairs
how to use find_if to find element in given vector of pairs

Time:11-12

For example consider vector<pair<string,int>>

And it contains:

ABC 1
BCD 2
CDE 3
XHZ 4

string s;
cin>>s;
if(find_if(vec.begin(),vec.begin() 3,cmp)!=vec.begin() 3) // I want to check only first 3 values  

I need cmp to find given string is present or not using find_if

EDIT:
How to pass the string s with the comparator (cmp) and the vector will always contains minimum 3 elements

CodePudding user response:

The simplest way is to use a lambda expression. For example

#include <string>
#include <utility>
#include <vector>
#include <iterator>
#include <algorithm>

//...

std::string s;
std::cin >> s; 

auto cmp = [&s]( const auto &p ) { return p.first == s; }; 

if ( std::find_if( std::begin( vec ), std::next( std::begin( vec ), 3 ), cmp ) != std::next( std::begin( vec ), 3 ) )
{
    //...
}

Another approach is to create a function object before main as for example

class cmp
{
public:
    cmp( const std::string &s ) : s( s )
    {
    }

    bool operator() ( const std::pair<std::string, int> &p ) const
    {
        return p.first == s;
    }

private:
    const std::string &s;
};


//...
if ( std::find_if( std::begin( vec ), std::next( std::begin( vec ), 3 ), cmp( s ) ) != std::next( std::begin( vec ), 3 ) )
{
    //...
}
  • Related