如果修改了set中的鍵值(即作為排序用的主鍵的值),就會(huì)破壞set容器的有序性。
看如下程序:
#include<iostream>
#include<set>
using namespace std;
class Test
{
public:
int key;
Test(int k):key(k)
{
}
void setkey(int newKey)
{
key=newKey;
}
bool operator<(const Test & t) const
{
return key<t.key;
}
};
int main()
{
set<Test>ts;
for(int i=1;i<10;i++)
{
Test t(10-i);
ts.insert(t);
}
set<Test>::iterator it;
for(it=ts.begin();it!=ts.end();it++)
if(it->key==5)
{
it->key=20;
break;
}
for(it=ts.begin();it!=ts.end();it++)
cout<<it->key<<endl;
}
上述程序中,把鍵值為5的元素的鍵值修改成了20. 最后輸出結(jié)果為1 2 3 4 20 6 7 8 9.即set容器的有序性被破壞了。
另外,看下面的程序
1 #include<iostream>
2 #include<vector>
3 #include<string>
4 #include<cmath>
5 #include<set>
6 using namespace std;
7 class Test
8 {
9 public:
10 int key;
11 Test(int k):key(k)
12 {
13 }
14 void setkey(int newKey)
15 {
16 key=newKey;
17 }
18 bool operator<(const Test & t) const
19 {
20 return key<t.key;
21 }
22 };
23 int main()
24 {
25 set<Test>ts;
26 for(int i=1;i<10;i++)
27 {
28 Test t(10-i);
29 ts.insert(t);
30 }
31 set<Test>::iterator it;
32 for(it=ts.begin();it!=ts.end();it++)
33 if(it->key==5)
34 {
35 ((Test)(*it)).setkey(20);
36 break;
37 }
38 cout<<it->key<<endl;
39 }
在第35行中,先把*it強(qiáng)制轉(zhuǎn)換成了Test類型,然后改變了key的值。但是在第38行的輸出中,結(jié)果不是20,而是5.這時(shí)因?yàn)?這種類型轉(zhuǎn)換的結(jié)果是一個(gè)臨時(shí)的匿名對(duì)象,他是*it的一個(gè)拷貝,setkey操作被作用到了這個(gè)臨時(shí)變量上。
解決這個(gè)問(wèn)題,可以把地35句換成 const_cast<Test&>(*it).setkey(20); 或者static_cast<Test&>(*it).setkey(20); 這樣輸出結(jié)果就是20.
注意,const_cast與static_cast的區(qū)別。
他們都用于強(qiáng)制類型轉(zhuǎn)換。但是const_cast只能作用于引用或者指針,而static_cast即可作用于引用或者指針,還可作用于對(duì)象。所以,const_cast<Test>(*it).setkey(20); 這條語(yǔ)句編譯時(shí)會(huì)出錯(cuò)。而static_cast<Test&>(*it).setkey(20); 可以通過(guò)編譯,但如果把這句話放在上面程序的第35句,輸出的結(jié)果仍是5,而不是20.