在我们使用C++中的STL的时候,可以使用迭代器iterator进行遍历,但是当我们通过iterator对vector和map删除元素的时候,要格外的小心,往往操作不当,导致iterator失效,后果就是程序奔溃。
1. 对于vector,erase会返回下一个iterator。所以一般采用的方法是:
因为在使用erase的时候,删除元素前面的iterator有效,但是后面的iterator就不可预知了。
- #include <iostream>
- #include <vector>
- #include <iterator>
- using namespace std;
- void displayAllDate(vector<int>& inputDate)
- {
- vector<int>::iterator itor = inputDate.begin();
- cout << endl;
- while (itor != inputDate.end())
- {
- cout << *itor << " ";
- ++itor;
- }
- }
- int main()
- {
- vector<int> inputDate;
- for (int i = 0; i < 10; i++)
- {
- inputDate.push_back(i);
- }
- vector<int>::iterator iter = inputDate.begin();
- while (iter != inputDate.end())
- {
- if (0 == (*iter)%2)
- {
- iter = inputDate.erase(iter);
- }
- else
- {
- ++iter;
- }
- }
- displayAllDate(inputDate);
- return 0;
- }
2. 对于map,删除erase之后,只会影响到当前的iterator,因此我们一般推荐以下方法:
- #include <iostream>
- #include <map>
- #include <iterator>
- using namespace std;
- void displayAllDate(map<int, int>& inputDate)
- {
- map<int, int>::iterator itor = inputDate.begin();
- cout << endl;
- while (itor != inputDate.end())
- {
- cout << itor->second << " ";
- ++itor;
- }
- }
- int main()
- {
- map<int, int> inputDate;
- for (int i = 0; i < 10; i++)
- {
- inputDate[i] = i + 10;
- }
- map<int, int>::iterator iter = inputDate.begin();
- while (iter != inputDate.end())
- {
- if (0 == (iter->second) % 2)
- {
- inputDate.erase(iter++);
- }
- else
- {
- ++iter;
- }
- }
- displayAllDate(inputDate);
- return 0;
- }
但是要注意的一点,map的erase操作在window下面也可以用vector的方法实现,但是在linux下是编译不过的。所以推荐使用上面的方法。
- #include <iostream>
- #include <map>
- #include <iterator>
- using namespace std;
- void displayAllDate(map<int, int>& inputDate)
- {
- map<int, int>::iterator itor = inputDate.begin();
- cout << endl;
- while (itor != inputDate.end())
- {
- cout << itor->second << " ";
- ++itor;
- }
- }
- int main()
- {
- map<int, int> inputDate;
- for (int i = 0; i < 10; i++)
- {
- inputDate[i] = i + 10;
- }
- map<int, int>::iterator iter = inputDate.begin();
- while (iter != inputDate.end())
- {
- if (0 == (iter->second) % 2)
- {
- iter = inputDate.erase(iter);
- }
- else
- {
- ++iter;
- }
- }
- displayAllDate(inputDate);
- return 0;
- }
参考: