c++中的erase函数总结

set::erase

(1)
void erase (iterator position);

(2)
size_type erase (const value_type& val);

(3)
void erase (iterator first, iterator last);

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// erasing from set
#include <iostream>
#include <set>

int main ()
{
std::set<int> myset;
std::set<int>::iterator it;

// insert some values:
for (int i=1; i<10; i++) myset.insert(i*10); // 10 20 30 40 50 60 70 80 90

it = myset.begin();
++it; // "it" points now to 20

myset.erase (it);

myset.erase (40);

it = myset.find (60);
myset.erase (it, myset.end());

std::cout << "myset contains:";
for (it=myset.begin(); it!=myset.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';

return 0;
}

Output:

myset contains: 10 30 50

vector::erase

iterator erase (iterator position);

iterator erase (iterator first, iterator last);

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/ erasing from vector
#include <iostream>
#include <vector>

int main ()
{
std::vector<int> myvector;

// set some values (from 1 to 10)
for (int i=1; i<=10; i++) myvector.push_back(i);

// erase the 6th element
myvector.erase (myvector.begin()+5);

// erase the first 3 elements:
myvector.erase (myvector.begin(),myvector.begin()+3);

std::cout << "myvector contains:";
for (unsigned i=0; i<myvector.size(); ++i)
std::cout << ' ' << myvector[i];
std::cout << '\n';

return 0;
}

myvector contains: 4 5 7 8 9 10

string::erase

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// string::erase
#include <iostream>
#include <string>

int main ()
{
std::string str ("This is an example sentence.");
std::cout << str << '\n';
// "This is an example sentence."
str.erase (10,8); // ^^^^^^^^
std::cout << str << '\n';
// "This is an sentence."
str.erase (str.begin()+9); // ^
std::cout << str << '\n';
// "This is a sentence."
str.erase (str.begin()+5, str.end()-9); // ^^^^^
std::cout << str << '\n';
// "This sentence."
return 0;
}
1
2
3
4
5
Output:
This is an example sentence.
This is an sentence.
This is a sentence.
This sentence.