map::erase
從移除指定位置處的一或多個項目範圍進行對應的或移除符合指定之索引鍵的項目。
iterator erase(
iterator _Where
);
iterator erase(
iterator _First,
iterator _Last
);
size_type erase(
const key_type& _Key
);
參數
_Where
從對應要移除之項目的位置。_First
從對應移除之第一個項目的位置。_Last
在從對應中移除的最後一個項目以外的位置。_Key
從對應中移除之項目的索引鍵值。
傳回值
在前兩個成員函式、指定保持在所有項目外的第一個項目中移除的雙向 Iterator 或對應的結尾的指標,如果沒有此類項目存在則為。
注意事項 |
---|
這個傳回型別不符合 C++ 標準。 |
針對第三 + 成成員函式,傳回從對應中移除項目的數目。
備註
在其他情況下,這個方法會擲回 out_of_range 例外狀況。
範例
當編譯這個範例使用 /Wp64 旗標或在 64 位元平台時,警告的編譯器 C4267 產生。 如需這項警告的詳細資訊,請參閱 編譯器警告 (層級 3) C4267。
// map_erase.cpp
// compile with: /EHsc
#include <map>
#include <iostream>
int main()
{
using namespace std;
map<int, int> m1, m2, m3;
map<int, int>::iterator pIter, Iter1, Iter2;
int i;
map<int, int>::size_type n;
typedef pair<int, int> Int_Pair;
for (i = 1; i < 5; i++)
{
m1.insert(Int_Pair(i, i));
m2.insert(Int_Pair(i, i*i));
m3.insert(Int_Pair(i, i-1));
}
// The 1st member function removes an element at a given position
Iter1 = ++m1.begin();
m1.erase(Iter1);
cout << "After the 2nd element is deleted, the map m1 is:";
for (pIter = m1.begin(); pIter != m1.end(); pIter++)
cout << " " << pIter->second;
cout << "." << endl;
// The 2nd member function removes elements
// in the range [_First, _Last)
Iter1 = ++m2.begin();
Iter2 = --m2.end();
m2.erase(Iter1, Iter2);
cout << "After the middle two elements are deleted,"
<< " the map m2 is:";
for (pIter = m2.begin(); pIter != m2.end(); pIter++)
cout << " " << pIter->second;
cout << "." << endl;
// The 3rd member function removes elements with a given _Key
n = m3.erase(2);
cout << "After the element with a key of 2 is deleted,\n"
<< "the map m3 is:";
for (pIter = m3.begin(); pIter != m3.end(); pIter++)
cout << " " << pIter->second;
cout << "." << endl;
// The 3rd member function returns the number of elements removed
cout << "The number of elements removed from m3 is: "
<< n << "." << endl;
// The dereferenced iterator can also be used to specify a key
Iter1 = ++m3.begin();
m3.erase(Iter1);
cout << "After another element with a key equal to that"
<< endl;
cout << "of the 2nd element is deleted, "
<< "the map m3 is:";
for (pIter = m3.begin(); pIter != m3.end(); pIter++)
cout << " " << pIter->second;
cout << "." << endl;
}
需求
標題: <map>
命名空間: std