C++ 使用 find_if 查找值

标签 c++ lambda stl

我正在尝试查找字符串 words 是否包含任何 instruction 形式 ma​​chine_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/

相关文章:

c++ - CUDA 的性能取决于声明变量

c++ - 涉及 iostream 和 wstring 的奇怪 C++ 行为

c++ - "map/set iterators incompatible" map 销毁,取决于构造函数调用

c++ - 如何检查对象的属性更新是否存在 std::map 键,否则插入一个新键?

c++ - 如何解决 linux 定时器信号处理程序

c++ - 可以返回兄弟对象的函数的自动返回类型

Python:列表函数和 lambda 表达式

amazon-web-services - "errorMessage": "module initialization error"

list - 如何使用lambda,Java在列表迭代结束时返回值

c++ - 具有数组元素的 STL 堆栈