我正在尝试查找字符串 words 是否包含任何 instruction 形式 machine_opTable,pair-string,int 的 vector 。
我的 lambda 函数在 find_if 中应该是什么样子? 如果您有任何其他方法,请告诉我。
截至目前,我的代码看起来像......
# define RX 4
# define RR 2
...
vector < pair <string, int> > machine_opTable = { {"L", RX},
{ "A", RX},
{"ST", RX}
};
words = " L 1, SMB1";
string inMachineop;
for ( auto instruction: words){
inMachineop = find_if ( begin(machine_opTable), end(machine_opTable), [] (const pair<string,int>& p) { return ( p.first == instruction ? p.first : "NOTFOUND"); });
}
我很乐意返回指向那对的迭代器...请告诉我它是如何完成的。
谢谢。
最佳答案
find_if
根据引用返回值是
An iterator to the first element in the range for which
pred
does not return false.
pred
是您的 lambda,它必须返回 bool 值。
如果你想在你的lambda中使用指令
,你必须捕获这个变量
[instruction] (const pair<string,int>& p) { return p.first == instruction; }
当我们知道它返回迭代器时,find_if
的调用如下所示
auto it = find_if ( begin(machine_opTable), end(machine_opTable), [instruction] (const pair<string,int>& p) { return p.first == instruction; });
if (it != machine_opTable.end())
{
// access to found pair
}
else
; // pair not found
关于C++ 使用 find_if 查找值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48556978/