c++ - 如何使用 STL 从容器集中删除自定义对象?

标签 c++ stl set remove-if

以下是类和容器

class student {
    std::string name;
    int id;
}

set<Student*, compare> s; // sorted by id that i have done correctly
class compare {
public:
    bool operator()( Student* s1, Student* s2) {
        return s1->id < s2->id;
    }
};

如何从集合中删除名称为“suri”的对象;

我做了什么?

std::remove(s.begin(), s.end(), nameIs("suri"));

仿函数是

struct nameIs {
    nameIs ( std::string s ) : toFind(s) { }
    bool operator() ( Student* st)
    { return st->name.compare(toFind) == 0; }
    std::string toFind;
};

但是我遇到编译时错误 错误 2 错误 C3892:“_Next”:无法分配给 const c:\program files (x86)\microsoft Visual Studio 10.0\vc\include\algorithm 1816 的变量

我做错了什么? 如何使用 STL 从容器集中删除自定义对象?

最佳答案

enter image description here

如果你看一下,*first == val但实际上在你的情况下,它应该是*first->name == val

嗯,你可以试试这个

std::set<Student*>::iterator it = s.begin();
for (it = s.begin(); it != s.end(); ) {
     if ((*it)->name == "suri") {
        s.erase(it++);
         break;
    }
    else {
        ++it;
    }
}

关于c++ - 如何使用 STL 从容器集中删除自定义对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30148330/

相关文章:

C++ 字符串流tellg()

c++ - pybind11 中 protected 虚拟析构函数

c++ - 初始化模板数组

python - 是什么让一个元素有资格在 Python 中进行集合成员资格测试?

java - 如何确定位置 Z 是否在起点 X 和终点 Y 的区域内

.net - 从 C++ 中的 .Net TextBox 获取 double 值

c++ - 将 BCD 字符串转换为十进制

c++ - 从列表中找到最近的点到一个引用列表

c++ - 在 C++ 中生成一个字符串映射到 std::list of pointers

java - 如何使用对象在 Java 中设置差异?