次のプログラムを検討してください。intへのポインタのセットを作成し、指定された整数の値でセットをソートするカスタムindrect_lessコンパレータを使用します。これが完了したら、ポイントされた整数の1つの値を変更します。次に、セットの順序がソートされなくなったことがわかります(セットは何かが変更されたことを認識していないためだと思います)。
(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;
実行された後、明確に定義された動作で、セットをソートされた順序にリバランスする方法はありますか?