如果集合中元素的值发生更改,则排序可能不再正确.如这个小程序所示:
#include <algorithm>
#include <iostream>
#include <set>
#include <string>
struct Comp
{
bool operator()(const std::string * lhs, const std::string * rhs)
{
return *lhs < *rhs;
}
};
int main()
{
typedef std::set<std::string*, Comp> MySet;
MySet mySet;
std::string * a = new std::string("a");
mySet.insert(a);
std::string * c = new std::string("c");
mySet.insert(c);
std::string * b = new std::string("b");
mySet.insert(b);
for (MySet::iterator it = mySet.begin(); it != mySet.end(); ++it)
{
std::cout << *(*it) << std::endl;
}
// Ouput has correct order:
// a
// b
// c
*b = "z";
std::cout << std::endl;
std::string * d = new std::string("d");
mySet.insert(d);
for (MySet::iterator it = mySet.begin(); it != mySet.end(); ++it)
{
std::cout << *(*it) << std::endl;
}
// Output no longer ordered correctly:
// a
// d
// z
// c
return 0;
}
Run Code Online (Sandbox Code Playgroud)
如何告诉设置"刷新"其内部排序?
Dan*_*ker 10
这里的主题非常相似(虽然不是很重复,因为你通过自定义比较存储指向可变对象的指针):
基本上,不要做你想做的事.相反,当您想要修改set保存指针的对象时,首先删除指针,然后修改对象,然后重新插入指针.
简单地说,你不能.如果将项目放入集合中,则不应以更改其顺序的方式更改项目.如果需要以这种方式更改项目,则需要将其从set(set :: erase)中删除,然后使用新值重新插入新项目(std :: insert).
| 归档时间: |
|
| 查看次数: |
1011 次 |
| 最近记录: |