0%

stl容器的遍历删除

stl容器的遍历删除

https://zhuanlan.zhihu.com/p/67026112

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
30
31
32
33
34
35
36
37
38
#include <vector>
#include <map>
#include <iterator>
#include <iostream>
#include <algorithm>

int main(int argc, char *argv[])
{
//vector遍历删除
std::vector<int> v(8);
std::generate(v.begin(), v.end(), std::rand);
std::cout << "after vector generate...\n";
std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, "\n"));

for (auto x = v.begin(); x != v.end(); )
{
if (*x % 2)
x = v.erase(x);
else
++x;
}

std::cout << "after vector erase...\n";
std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, "\n"));

//map遍历删除
std::map<int, int> m = {{1,2}, {8,4}, {5,6}, {6,7}};

for (auto x = m.begin(); x != m.end(); )
{
if (x->first % 2)
m.erase(x++);
else
++x;
}

return 0;
}
跑步练琴写代码