【发布时间】:2009-06-20 09:57:09
【问题描述】:
如果集合中元素的值发生变化,则排序可能不再正确。如这个小程序所示:
#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;
}
如何告诉集合“刷新”其内部排序?
【问题讨论】:
-
值应该不改变。
value_type应该是std::set<const std:string*>(虽然我相信 VS 不遵守那个?) -
值类型是用户传递的,加上一个顶级的const。如果用户传递
std::string*,则值类型将为std::string* const。没有规则禁止用户传递不强制值排序位置不变性的东西;只有一条规则说以这种方式修改值会产生未定义的行为。