set::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。
// set_erase.cpp
// compile with: /EHsc
#include <set>
#include <iostream>
int main()
{
using namespace std;
set<int> s1, s2, s3;
set<int>::iterator pIter, Iter1, Iter2;
int i;
set<int>::size_type n;
for (i = 1; i < 5; i++)
{
s1.insert(i);
s2.insert(i * i);
s3.insert(i - 1);
}
// The 1st member function removes an element at a given position
Iter1 = ++s1.begin();
s1.erase(Iter1);
cout << "After the 2nd element is deleted, the set s1 is:";
for (pIter = s1.begin(); pIter != s1.end(); pIter++)
cout << " " << *pIter;
cout << "." << endl;
// The 2nd member function removes elements
// in the range [_First, _Last)
Iter1 = ++s2.begin();
Iter2 = --s2.end();
s2.erase(Iter1, Iter2);
cout << "After the middle two elements are deleted, "
<< "the set s2 is:";
for (pIter = s2.begin(); pIter != s2.end(); pIter++)
cout << " " << *pIter;
cout << "." << endl;
// The 3rd member function removes elements with a given _Key
n = s3.erase(2);
cout << "After the element with a key of 2 is deleted, "
<< "the set s3 is:";
for (pIter = s3.begin(); pIter != s3.end(); pIter++)
cout << " " << *pIter;
cout << "." << endl;
// The 3rd member function returns the number of elements removed
cout << "The number of elements removed from s3 is: "
<< n << "." << endl;
// The iterator can also be used to specify a key
Iter1 = ++s3.begin();
s3.erase(Iter1);
cout << "After another element (unique for set) with a key"
<< endl;
cout << "equal to that of the 2nd element is deleted, "
<< "the set s3 is:";
for (pIter = s3.begin(); pIter != s3.end(); pIter++)
cout << " " << *pIter;
cout << "." << endl;
}
需求
標題: <set>
命名空間: std