我需要查找地图中呈现的矢量元素。难题在于该向量由结构组成,所以您应该首先调用成员函数来从结构中提取值,以将其与地图元素进行比较。查找地图中呈现的矢量元素
因此,与循环这是很容易:
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;
}
在此先感谢
嗨,这个工程。我相信问题不在于大括号的数量,而在...&mp ...我错过了&。 – Alex 2013-05-14 11:58:54
@亚历克斯:很高兴它适合你。通过值而不是指针传递'mp'只是一种优化,因为'mp'可以被复制。问题是额外的括号。 [这](http://coliru.stacked-crooked.com/view?id = b2a625da792e0c3b7e7b203b9053ca65-7063104e283ed82d51a6fde7370c6e59)在线编译器失败,因为它无法找到运算符!=采用迭代器(从find_if返回)和int(0)。删除多余的括号会导致'!= 0'使用'boost :: bind'运算符重载,而不是试图与'find_if'的返回值进行比较。 – 2013-05-14 12:38:54