c++ - 如何在结构体的 `std::list`处进行搜索?

标签 c++ algorithm c++11 lambda stdlist

问题是我无法根据用户输入的vIDstd::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/

相关文章:

c++ - 指定不绑定(bind)临时对象的 `const int&`

c++ - 无法让 SFINAE 在功能检测器中工作

c++ - 我可以在 ICU 中从 char* 转换为 UChar 吗?

c++ - 内存未释放 std::list<std::shared_ptr<std::string>> C++

algorithm - 在有向加权图中找到两个节点之间的最短路径

algorithm - 这里的时间复杂度是多少? O(NlogN) 还是 O(logN^2)?

C++ 给定日期和今天日期之间的天数

c++ - 关于链表的指针问题

c++ - 如何使用 CMake 将 NMake 从 VS9 切换到 VS10

python - 根据距离和出现频率选择一个项目(从一组项目中)