如何查找结构列表项
How to find a struct list item
>我有一个结构列表,描述如下:
struct Files
{
string id;
string path;
string chksum;
};
还有一个变量,其中包含此结构的列表,该结构描述了具有字段id
、path
和chksum
的文件列表。
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 :(";
}
}
相关文章:
- 在C++中循环访问自定义结构列表的小问题
- 如何从结构列表中筛选信息
- C++使用旧编译器GCC 4.4.0在结构列表中查找字符串
- 唯一的结构列表
- 如何查找结构列表项
- 将数组/对象/结构列表从C#库中传递给C MFC应用程序
- 是否可以将结构列表从C 传递到C#
- C++ 分段错误 - 具有集合的结构列表
- 双链接结构列表的内存泄漏
- 如何在 c++ 中使用结构列表
- C++如何访问结构列表的字符串成员
- 按元素对结构列表进行排序
- 对结构列表进行排序
- C++数据结构列表,在我的代码中
- 要排序或搜索的结构列表(C++)
- C++结构列表中插入元素
- 分配结构列表的向量
- 当我尝试从结构列表中访问内存时出现错误:" Program received signal SIGSEGV, Segmentation fault."
- 如果与变量匹配,如何从结构列表中删除1个结构
- 如何使用整数参数(c++)访问结构列表