从指定的位置移除元素或元素的大小设置或移除与指定的键的元素。
iterator erase(
const_iterator Where
);
iterator erase(
const_iterator First,
const_iterator Last
);
size_type erase(
const key_type& Key
);
参数
Where
要移除的元素的位置。First
要移除的第一个元素的位置。Last
最后一个元素前面的要移除元素的位置。Key
要移除元素的关键值。
返回值
对于前两个成员函数、指定保持在所有元素外的第一个元素中移除一双向迭代器或如果不存在这样的元素设置为末尾的元素。
为第三个成员函数,返回从集合中移除元素的数目。
示例
// 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