考虑以下程序。它创建一组指向整数的指针,并使用自定义的 indrect_less 比较器,该比较器根据指向的整数的值对集合进行排序。完成此操作后,我将更改指向整数之一的值。然后,可以看到集合的顺序不再排序(我想是因为集合不知道有什么改变了)。
(不要介意 C++0x 循环,我在 VS2010 上运行)
#include <iostream>
#include <set>
using namespace std;
struct indirect_less {
bool operator()(int* l, int* r) const
{
return *l < *r;
}
};
int main()
{
set<int*, indirect_less> myset;
int* a = new int(5);
int* b = new int(6);
int* c = new int(7);
myset.insert(a);
myset.insert(b);
myset.insert(c);
cout << "Set contains: ";
// (outputs: 5 6 7)
for (auto i = myset.begin(), end = myset.end(); i != end; ++i)
{
cout << **i << " ";
}
cout << endl << "Modifying *a" << endl;
*a = 9; // point of interest
cout << "Set contains: ";
// (outputs: 9 6 7 - unsorted order)
for (auto i = myset.begin(), end = myset.end(); i != end; ++i)
{
cout << **i << " ";
}
cout << endl;
cin.get();
return 0;
}
1)我在调用未定义的行为是对的吗?行后整个状态是否myset
无效*a = 9;
?
2)这样做是擦除然后重新插入的唯一正确方法a
吗?
3)有什么方法,一旦*a = 9;
运行,重新平衡集合到排序顺序,具有明确定义的行为?