set::erase
從指定的位置移除項目或一個範圍的元素,或移除符合指定之索引鍵的項目。
iterator erase(
const_iterator Where
);
iterator erase(
const_iterator First,
const_iterator Last
);
size_type erase(
const key_type& Key
);
參數
Where
要移除之項目的位置。First
第一個要移除之項目的位置。Last
要移除的最後項目以外的位置。Key
項目要移除之索引鍵。
傳回值
在前兩個成員函式,雙向 Iterator 保持在被移除的項目以外的第一個項目,如果沒有此類項目存在則為集合結尾的項目。
針對第三個成員函式,傳回從集合中移除的項目數。
範例
// set_erase.cpp
// compile with: /EHsc
#include <set>
#include <string>
#include <iostream>
#include <iterator> // next() and prev() helper functions
using namespace std;
using myset = set<string>;
void printset(const myset& s) {
for (const auto& iter : s) {
cout << " [" << iter << "]";
}
cout << endl << "size() == " << s.size() << endl << endl;
}
int main()
{
myset s1;
// Fill in some data to test with, one at a time
s1.insert("Bob");
s1.insert("Robert");
s1.insert("Bert");
s1.insert("Rob");
s1.insert("Bobby");
cout << "Starting data of set s1 is:" << endl;
printset(s1);
// The 1st member function removes an element at a given position
s1.erase(next(s1.begin()));
cout << "After the 2nd element is deleted, the set s1 is:" << endl;
printset(s1);
// Fill in some data to test with, one at a time, using an intializer list
myset s2{ "meow", "hiss", "purr", "growl", "yowl" };
cout << "Starting data of set s2 is:" << endl;
printset(s2);
// The 2nd member function removes elements
// in the range [First, Last)
s2.erase(next(s2.begin()), prev(s2.end()));
cout << "After the middle elements are deleted, the set s2 is:" << endl;
printset(s2);
myset s3;
// Fill in some data to test with, one at a time, using emplace
s3.emplace("C");
s3.emplace("C#");
s3.emplace("D");
s3.emplace("D#");
s3.emplace("E");
s3.emplace("E#");
s3.emplace("F");
s3.emplace("F#");
s3.emplace("G");
s3.emplace("G#");
s3.emplace("A");
s3.emplace("A#");
s3.emplace("B");
cout << "Starting data of set s3 is:" << endl;
printset(s3);
// The 3rd member function removes elements with a given Key
myset::size_type count = s3.erase("E#");
// The 3rd member function also returns the number of elements removed
cout << "The number of elements removed from s3 is: " << count << "." << endl;
cout << "After the element with a key of \"E#\" is deleted, the set s3 is:" << endl;
printset(s3);
}
Output
Starting data of set s1 is:
[Bert] [Bob] [Bobby] [Rob] [Robert]
size() == 5
After the 2nd element is deleted, the set s1 is:
[Bert] [Bobby] [Rob] [Robert]
size() == 4
Starting data of set s2 is:
[growl] [hiss] [meow] [purr] [yowl]
size() == 5
After the middle elements are deleted, the set s2 is:
[growl] [yowl]
size() == 2
Starting data of set s3 is:
[A] [A#] [B] [C] [C#] [D] [D#] [E] [E#] [F] [F#] [G] [G#]
size() == 13
The number of elements removed from s3 is: 1.
After the element with a key of "E#" is deleted, the set s3 is:
[A] [A#] [B] [C] [C#] [D] [D#] [E] [F] [F#] [G] [G#]
size() == 12
需求
標頭: <set>
命名空間: std