以下是类和容器
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 从容器集中删除自定义对象?
最佳答案
如果你看一下,*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/