如何查找结构列表项

How to find a struct list item

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

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

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 :(";
}

似乎变量filename是在块范围内声明的。在这种情况下,您必须捕获它。最好通过引用来捕获它,例如

#include <iostream>
#include <string>
#include <list>
#include <iterator>
#include <algorithm>
struct Files
{
std::string id;
std::string path;
std::string chksum;
};
int main()
{
std::list<Files> myFiles = { { "10", "mytext.txt", "10" } };
std::string filename = "mytext.txt";
auto match = std::find_if( std::cbegin( myFiles ), std::cend( myFiles ), 
[&] ( const Files &s ) 
{
return s.path == filename;
} );
if ( match != std::cend( myFiles ) ) 
{
std::cout << "omg my file was found!!! :D";
}
else
{
std::cout << "your file is not here :(";
}
}

否则,如果变量文件名是在命名空间中声明的,则可以按原样使用 lambda

#include <iostream>
#include <string>
#include <list>
#include <iterator>
#include <algorithm>
struct Files
{
std::string id;
std::string path;
std::string chksum;
};
std::string filename = "mytext.txt";
int main()
{
std::list<Files> myFiles = { { "10", "mytext.txt", "10" } };

auto match = std::find_if( std::cbegin( myFiles ), std::cend( myFiles ), 
[] ( const Files &s ) 
{
return s.path == filename;
} );
if ( match != std::cend( myFiles ) ) 
{
std::cout << "omg my file was found!!! :D";
}
else
{
std::cout << "your file is not here :(";
}
}