C ++使用字符串项目在列表中查找结构? [英] C++ Find struct in list using a string item?
问题描述
我对c ++还是很陌生,我试图弄清楚如何使用字符串在列表中查找结构.
I'm very new to c++ and I'm trying to figure how to find a struct inside a list using a string.
我有一个像这样的结构:
I have a struct like this:
struct entrada {
string token;
string lexema;
string tipo;
};
和一个列表:
list<entrada> simbolos;
在"simbolos"中插入一些"entrada"
比方说,我想搜索带有某个"lexema"的"entrada",然后删除其他字符串.有没有简单的方法可以做到这一点?像函数之类的东西.我用while/for做的,但这不是我想做的.
Let's say I want to search for a 'entrada' with a certain 'lexema', and cout the other strings. Is there a simple way to do this? Like a function or something. I did it using while/for, but it isn't how I want to do.
推荐答案
根据您的注释,以下代码段向您展示了一种使用STL中的算法将元素搜索到容器中的简单方法
In accordance with your comments, the following snippet shows you a simple way to search an element into a container using the algorithm in the 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 ++使用字符串项目在列表中查找结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!