问题是我无法根据用户输入的vID
在std::list
中进行搜索。
我尝试了很多不同的方法,但没有成功。
struct VideoDetails
{
int VidID, Copies;
string MovieTitle, Genre, Production, FileName;
};
list <VideoDetails> MyList;
int vID;
cin >> vID;
第一次尝试:
find_if(MyList.begin(), MyList.end(), [](VideoDetails & VD) {return VD.VidID == vID; });
第二次尝试:
auto pred = [](const VideoDetails & ID) { return ID.VidID == vID; };
find_if(Mylist.begin(), MyList.end(), vID) != MyList.end();
第三次尝试:
list <VideoDetails>::iterator iter;
for(iter = MyList.begin(); iter != MyList.end(); ++iter)
{
if ((*iter).VidID == vID) {
//
} else {
//
}
}
第一次尝试错误:
Error (active) E1738 the enclosing-function 'this' cannot be referenced in a lambda body unless it is in the capture list mp 3
第三次尝试错误:
Error C2678 binary '==': no operator found which takes a left-hand operand of type 'int' (or there is no acceptable conversion) mp 3
最佳答案
第一种方法:您没有捕获 lambda 内的 vID
,这就是错误消息所提示的内容。
const auto iter = std::find_if(MyList.begin(), MyList.end(),
[vID](const VideoDetails& VD) {return VD.VidID == vID; });
// ^^^^
并且不要忘记从 std::find_if
返回迭代器,以备进一步使用。如果您更正上述内容,您的第一种方法就会起作用。
第二种方法:与第一种方法没有太大区别。 lambda 与上面有同样的问题。除此之外 std::find_if
需要一个一元谓词,而不是在容器中找到的值。更改为
auto pred = [vID](const VideoDetails & ID) { return ID.VidID == vID; }
// ^^^^
if(std::find_if(Mylist.begin(), MyList.end(), pred ) != MyList.end())
// ^^^^
{
// do something
}
如果您已经使用了 std::find_if
和 lambda,则无需进行第三次尝试。
关于c++ - 如何在结构体的 `std::list`处进行搜索?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56565342/