C 使用字符串项目在列表中查找结构

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

本文关键字:列表 查找 结构 项目 字符串      更新时间:2023-10-16

我是C 的新手,我正在尝试弄清楚如何使用字符串在列表中找到结构。

我有这样的结构:

struct entrada {
  string token;
  string lexema;
  string tipo;
};

和一个列表:

list<entrada> simbolos;

在这里插入一些" entrada"

假设我想搜索带有某种" lexema"的" entrada",然后搜索其他字符串。有什么简单的方法吗?像功能之类的东西。我是在/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