c++ - 如何查找结构列表项

标签 c++ algorithm struct lambda find

我有一个结构列表,如下所述:

struct Files
{
    string id;
    string path;
    string chksum;
};

还有一个包含此结构列表的变量,该结构描述了一个文件列表,其中包含字段 idpathchksum

list<Files> myFiles;

我需要实现一个函数来搜索确定的文件名是否存在于我的列表中。

我尝试使用 find_if 算法,但出现了非常奇怪的错误,我不确定如何有效地实现它。

string filename = "mytext.txt";

auto match = std::find_if(myFiles.cbegin(), myFiles.cend(), [] (const Files& s) {
  return s.path == filename;
});

if (match != myFiles.cend()) 
{
    cout << "omg my file was found!!! :D";
}
else
{
    cout << "your file is not here :(";
}

最佳答案

您需要将 filename 添加到 lambda 的捕获列表中:

string filename = "mytext.txt";

auto match = std::find_if(myFiles.cbegin(), myFiles.cend(), [filename] (const Files& s) {
    return s.path == filename;
});

if (match != myFiles.cend()) 
{
    cout << "omg my file was found!!! :D";
}
else
{
    cout << "your file is not here :(";
}

关于c++ - 如何查找结构列表项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57513289/

相关文章:

c++ - 有没有办法用父类的命名空间/类空间来引用子类?

android - Pou连接博弈算法

r - 按组计算的累计最小值和最大值

algorithm - 遍历三个或更多数字序列

c - 将#define 嵌入结构定义的目的是什么?

C++20 指定初始化器 char[]

c++ - Recvfrom() 挂起——当服务器关闭时如何处理这个问题

c - 使用自动更新的指针结构

struct - 为什么生命周期强制转换适用于结构而不适用于特征?

c++ - 如何在 C 中使用 char *