我对 C++ 很陌生,我正在尝试弄清楚如何使用字符串在列表中查找结构。
我有一个这样的结构:
struct entrada {
string token;
string lexema;
string tipo;
};
和一个列表:
list<entrada> simbolos;
在“simbolos”中插入一些“entrada”
假设我想搜索具有特定“lexema”的“entrada”,并计算其他字符串。有没有一种简单的方法可以做到这一点?比如函数什么的。我使用 while/for 做到了这一点,但这不是我想要的。
最佳答案
根据您的评论,以下代码片段向您展示了一种使用 STL std::find_if
中的算法在容器中搜索元素的简单方法。 .
auto match = std::find_if(simbols.cbegin(), simbols.cend(), [] (const entrada& s) {
return s.lexema == "2";
});
if (match != simbols.cend()) {
std::cout << match->token << '\n'
<< match->lexema << '\n'
<< match->tipo << '\n';
}
至少需要C++11。
关于C++ 使用字符串项在列表中查找结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46268626/