因為之前使用list.erase出過錯,現在用到map特意查了下erase的方法,結果更糊涂了。
經測驗下面寫法都結果都正確,疑惑到呼叫哪個那種方法更合適。因為有些寫法不是很理解用起來有些忐忑。
方法1為什么不出錯,結果是對的。按照以前使用list的經驗這樣寫不對啊。
方法2 按照代碼提示有3個這樣的方法:
void erase ( iterator position );
size_type erase ( const key_type& x );
void erase ( iterator first, iterator last );
就是沒有回傳iterator的方法,結果可以。
方法3 照的查的資料抄的,好像沒抄對,但是結果也沒出錯
方法4 抄的寫法,結果沒問題,理解起來有點費勁。
最后面的注釋是Dbgview輸出的結果 成功洗掉了1,2,3,4。程式沒有出錯
map<int, int>m;
map<int, int>::iterator it;
//初始化一些值
for (DWORD i = 0;i < 20; i++)
{
m[i] = i;
}
//輸出map的值
for (it = m.begin(); it != m.end(); it++)
{
trace("%d %d", it->first, it->second);
}
//方法1
for (it = m.begin(); it != m.end(); it++)
{
if (it->first == 1)
{
m.erase(it);
}
}
//方法2
for (it = m.begin(); it != m.end();)
{
if (it->first == 2)
{
it = m.erase(it);
}
else
{
it++;
}
}
//方法3
for (it = m.begin(); it != m.end(); it++)
{
if (it->first == 3)
{
m.erase(it++);
}
}
//方法4
for (it = m.begin(); it != m.end();)
{
if (it->first == 4)
{
m.erase(it++);
}
else
{
it++;
}
}
trace("洗掉后的結果=====================================");
for (it = m.begin(); it != m.end(); it++)
{
trace("%d %d", it->first, it->second);
}
//洗掉前的值
//0 0
//1 1
//2 2
//3 3
//4 4
//5 5
//6 6
//7 7
//8 8
//9 9
//10 10
//11 11
//12 12
//13 13
//14 14
//15 15
//16 16
//17 17
//18 18
//19 19
//洗掉后的結果=====================================
//0 0
//5 5
//6 6
//7 7
//8 8
//9 9
//10 10
//11 11
//12 12
//13 13
//14 14
//15 15
//16 16
//17 17
//18 18
//19 19
uj5u.com熱心網友回復:
// erasing from map
#include <iostream>
#include <map>
int main ()
{
std::map<char,int> mymap;
std::map<char,int>::iterator it;
// insert some values:
mymap['a']=10;
mymap['b']=20;
mymap['c']=30;
mymap['d']=40;
mymap['e']=50;
mymap['f']=60;
it=mymap.find('b');
mymap.erase (it); // erasing by iterator
mymap.erase ('c'); // erasing by key
it=mymap.find ('e');
mymap.erase ( it, mymap.end() ); // erasing by range
// show content:
for (it=mymap.begin(); it!=mymap.end(); ++it)
std::cout << it->first << " => " << it->second << '\n';
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/8166.html
標籤:C++ 語言
上一篇:vs2013 ultimate 編譯mfc寫的程式,提示要安裝vc_mbcsmfc.exe,安裝這個插件提示沒有庫,再就是提示正在運行
