C++ Find struct in list using a string item?

柔情痞子 提交于 2020-01-23 13:03:34

问题


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;
};

and a list:

list<entrada> simbolos;

Insert here some 'entrada' in 'simbolos'

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.


回答1:


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';
}

Live Demo

Although we are almost in 2018, I should say C++11 is required.



来源:https://stackoverflow.com/questions/46268626/c-find-struct-in-list-using-a-string-item

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!