C++使用list搭配find_if筛选元素报C2064错误如何修复
错误根因说明
你遇到的C2064错误核心原因是std::find_if的第三个参数要求传入一个可调用的谓词对象(接收1个参数返回bool值),但你当前传入的是(*it).name(学生姓名字符串),不符合调用要求;另外你注释中的Find函数写在了main函数内部,C++不支持函数嵌套定义,所以这个谓词本身也无法被正常调用。
需要修改的核心部分
- 移除嵌套在main内的谓词定义,改用lambda表达式作为
find_if的谓词(可以直接捕获当前循环的学生姓名做比较,写法更简洁),如果要使用独立函数可以单独定义在main外,需要额外传入要匹配的姓名参数,不如lambda方便。 - 修正
find_if的调用逻辑,匹配到对应学生后,删除的是find_if返回的迭代器that指向的元素,而不是未初始化的all迭代器。 - 修正遍历删除的逻辑,避免迭代器失效问题。
修复后的核心代码示例
#include <iostream> #include <list> #include <algorithm> #include <cstring> using namespace std; // 假设你定义的结构体如下,根据你实际的定义调整即可 struct Astu { char name[20]; }; struct Stu { char name[20]; }; // 你需要的排序比较函数,根据你的实际逻辑调整 bool SizeComp2(const Astu& a, const Astu& b) { return strcmp(a.name, b.name) < 0; } int main(void) { // 这里假设你已经提前初始化了stu(出勤/迟到名单)、astu(总学生名单)两个list容器 list<Stu> stu; list<Astu> astu; list<Stu>::iterator it; list<Astu>::iterator that; for (it = stu.begin(); it != stu.end(); it++) { // 用lambda作为谓词,捕获当前循环的学生姓名做匹配 that = find_if(astu.begin(), astu.end(), [&it](const Astu& a) { return strcmp(a.name, it->name) == 0; }); if (that != astu.end()) { // 直接删除匹配到的元素,不需要额外维护all迭代器 astu.erase(that); } } cout << "---------------------" << endl << "결석자: " << endl; //이름순으로 정렬 astu.sort(SizeComp2); //결석자들 출력 for (auto all = astu.begin(); all != astu.end(); all++) { cout << "이름: " << (*all).name << endl; } return 0; }
补充说明:如果你的name成员是
std::string类型,把lambda里的strcmp替换成直接判断a.name == it->name即可,不需要调用strcmp。
内容的提问来源于stack exchange,提问作者Kimsuyeon
相关产品推荐
相关产品推荐

