Trying to see if the vector <string> has values ​​in the map <row, row>

Just for fun, I tried to write a single line with std :: find_if with boost :: bind to check if all the keys given in the vector on the map had any values, but actually could not come up with a neat line of code.
Here is what I tried

vector<string> v;  
v.push_back("a");  
v.push_back("2");  
...  
map<string, string> m;  
m.insert("b","f");  
...  
std::find_if(v.begin(), v.end(), boost::bind(&string::empty, boost::bind(&map<string,String>::operator[], _1), _2 )) != v.end();  

Obviously this is a big setback ... did someone try something like this?

+3
source share
3 answers

The following line of code returns trueonly if all of the elements are vmissing from m:

bool a = v.end() == std::find_if( v.begin(), v.end(), boost::bind( &str_map_t::const_iterator::operator!=, boost::bind<str_map_t::const_iterator>( &str_map_t::find, &m, _1 ), m.end() ) );

Explanation:

Here we have two functors:

  • boost::bind<str_map_t::const_iterator>( &str_map_t::find, &m, _1 )
    const_iterator, m m.end(), . str_map_t::const_iterator boost::bind, .

  • boost::bind( &str_map_t::const_iterator::operator!=, _1, _2 )
    true, _1!=_2 false .

1 2, :

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <string>
#include <map>    
#include <boost/bind.hpp>    
using namespace std;

int main(int argc, char *argv[])
{
    vector<string> v;
    v.push_back("x");
    v.push_back("a");
    v.push_back("6");

    typedef map<string, string> str_map_t;
    str_map_t m;
    m.insert( str_map_t::value_type( "b", "f" ) );

    bool a = 
      v.end() == std::find_if( 
        v.begin(), v.end(), 
          boost::bind( 
            &str_map_t::const_iterator::operator!=, 
            boost::bind<str_map_t::const_iterator>( &str_map_t::find, &m, _1 ), 
            m.end() 
          ) 
      );

    std::cout << a << endl;

    return 0;
}

, , , . ( bind):

struct not_in_map {
    not_in_map( const str_map_t& map ) : map_(map) {}
    bool operator()( const string& val ) { return map_.end() != map_.find( val ); }
private:
    const str_map_t& map_;
};
bool a = v.end() == std::find_if( v.begin(), v.end(), not_in_map(m) );
+5
std::for_each(v.begin(), v.end(), [](std::string& ref) { if m.find(ref) != m.end() /* do something*/ });

Lambdas ftw.

+5

boost:: lambda - ++ 0x, , , .

, , ++, , .. , , , - . ++ , . , ++ 0x , , ( ) .

+1

Source: https://habr.com/ru/post/1751641/


All Articles