我需要找到地图中显示的向量元素。困难的部分是向量由结构组成,因此您应该首先调用成员函数从结构中提取值,然后将其与映射元素进行比较。
因此,使用 for 循环非常简单:
vector<A>::iterator it;
for( it = vec.begin(); it != vec.end(); ++it )
{
if( mp.count( it->getKey() ) )
{
break;
}
}
我的问题:有没有办法在一行中做到这一点,比如
//this doesn't work as count accepts key_type
vector<A>::iterator it = find_if( vec.begin(), vec.end(), boost::bind( &map<string, string>::count, mp, boost::bind( &A::getKey, _1 ) )) != 0);
完整示例,进行测试
#include <string>
#include <vector>
#include <iostream>
#include <algorithm>
#include <boost/bind.hpp>
#include <boost/assign.hpp>
using namespace std;
class A{
public:
A( const std::string& key )
: key( key ) {}
std::string getKey(){ return key; }
private:
std::string key;
};
int main(int argc, const char *argv[]) {
map<string, string> mp = boost::assign::map_list_of( "Key1", "Val1" ) ( "Key2", "Val2" ) ( "Key3", "Val3" );
vector<A> vec = boost::assign::list_of( "AAA" ) ( "Key2" ) ( "BBB" );
// vector<A>::iterator it = find_if( vec.begin(), vec.end(), boost::bind( &map<string, string>::count, mp, boost::bind( &A::getKey, _1 ) )) != 0);
vector<A>::iterator it;
for( it = vec.begin(); it != vec.end(); ++it )
{
if( mp.count( it->getKey() ) )
{
break;
}
}
cout << ( it != vec.end() ? "found" : "not found" ) << endl;
return 0;
}
提前致谢