我有一堂课有地图。我需要通过搜索特定值(而不是键)来在映射中找到迭代器。使用成员函数谓词 IsValueFound,我正在尝试这个。
class A
{
public:
void findVal();
private:
int state;
map<int, int> exmap;
bool IsValueFound(pair<int key, int val> itr)
{
return state == itr.second;
}
};
void A::findVal
{
itr = find_if(exmap.begin, exmap.end, mem_fun1_ref(&A::IsValueFound));
}
Run Code Online (Sandbox Code Playgroud)
我收到编译错误。我不确定这些函数适配器的语法是什么。请帮忙。
编辑:抱歉。请忽略 finf_if stmt 之外的编译错误。我需要首先纠正 find_if stmt 。而且代码没有 boost :(
编辑:我的答案显然有一个错误mem_fun1_ref(&A::IsValueFound),不能作为 的谓词std::find_if。我正在努力纠正这个问题。
你忘了用exmap.beginand加上括号exmap.end。我想如果你读过编译错误报告,它会告诉你一些事情。
我会这样写:
typedef map<int, int>::const_iterator MyIterator
void A::findVal()
{
const MyIterator itrBegin = exmap.begin();
const MyIterator itrEnd = exmap.end();
MyIterator itrFound = find_if( itrBegin ,
itrEnd ,
mem_fun1_ref(&A::IsValueFound));
}
Run Code Online (Sandbox Code Playgroud)
但我还没有尝试mem_fun1_ref(&A::IsValueFound)编译。而且我不习惯使用mem_fun1_ref,我总是用他们的重新定义我自己的函子operator()。