(原創) 如何删除std::vector内的element?(使用find) (C/C++) (STL)
若要删除std::vector中的element,正规的方式该用find() generic algorithm,若find()找到了,会传回该iterator,若找不到,将传回vector.end()。这种写法远比用for loop干净很多。
See Also
(原創) 何删除std::vector内的element?(使用for loop) (C/C++) (STL)
Reference
C++ Primer 4th P.327
1/*
2(C) OOMusou 2006 http://oomusou.cnblogs.com
3
4Filename : VectorFindAndErase.cpp
5Compiler : Visual C++ 8.0
6Description : Demo how to erase iterator in a RIGHT way.
7Release : 11/14/2006
8*/
9#include <iostream>
10#include <vector>
11#include <algorithm>
12
13int main() {
14 const int iaSize = 11;
15 int ia[] = {0, 1, 1, 2, 3, 5, 8, 13, 21, 55, 89};
16
17 std::vector<int> ivec;
18 ivec.insert(ivec.end(), ia, ia + iaSize);
19
20 // Compile OK, but run-time error!!
21 // for(std::vector<int>::iterator iter = ivec.begin();
22 // iter != ivec.end(); ++iter) {
23 // if (*iter == 8) {
24 // ivec.erase(iter);
25 // }
26 // }
27
28 // This is a RIGHT way to do it.
29 std::vector<int>::iterator iter = find(ivec.begin(), ivec.end(), 8);
30 if (iter != ivec.end()) {
31 ivec.erase(iter);
32 }
33
34 // cout the result
35 for(std::vector<int>::const_iterator iter = ivec.begin();
36 iter != ivec.end(); ++iter) {
37
38 std::cout << *iter << std::endl;
39 }
40
41 return 0;
42}
2(C) OOMusou 2006 http://oomusou.cnblogs.com
3
4Filename : VectorFindAndErase.cpp
5Compiler : Visual C++ 8.0
6Description : Demo how to erase iterator in a RIGHT way.
7Release : 11/14/2006
8*/
9#include <iostream>
10#include <vector>
11#include <algorithm>
12
13int main() {
14 const int iaSize = 11;
15 int ia[] = {0, 1, 1, 2, 3, 5, 8, 13, 21, 55, 89};
16
17 std::vector<int> ivec;
18 ivec.insert(ivec.end(), ia, ia + iaSize);
19
20 // Compile OK, but run-time error!!
21 // for(std::vector<int>::iterator iter = ivec.begin();
22 // iter != ivec.end(); ++iter) {
23 // if (*iter == 8) {
24 // ivec.erase(iter);
25 // }
26 // }
27
28 // This is a RIGHT way to do it.
29 std::vector<int>::iterator iter = find(ivec.begin(), ivec.end(), 8);
30 if (iter != ivec.end()) {
31 ivec.erase(iter);
32 }
33
34 // cout the result
35 for(std::vector<int>::const_iterator iter = ivec.begin();
36 iter != ivec.end(); ++iter) {
37
38 std::cout << *iter << std::endl;
39 }
40
41 return 0;
42}
See Also
(原創) 何删除std::vector内的element?(使用for loop) (C/C++) (STL)
Reference
C++ Primer 4th P.327