容器(container)的erase()函數, 是刪除一個元素, 會移動迭代器的指針, 指向下一個元素;
迭代器(iterator)是一種指針, 賦值是傳遞的地址, 指向相同的元素;
代碼:
/* * test.cpp * * Created on: 2014.04.18 * Author: Spike */ /*eclipse cdt, gcc 4.8.1*/ #include <iostream> #include <vector> using namespace std; int main() { std::vector<int> vi = {1, 6, 6, 3}; std::vector<int>::iterator iter1; std::vector<int>::iterator iter2; //少刪除了一個6 for (iter1 = vi.begin(); iter1 != vi.end(); ++iter1) { if (6 == *iter1) { iter2 = iter1; vi.erase(iter2); //--iter1; } } std::cout << "vector size is : " << vi.size() << std::endl; for (iter1 = vi.begin(); iter1 != vi.end(); ++iter1) { std::cout << *iter1 << " "; } std::cout << std::endl; return 0; }
輸出:
vector size is : 3 1 6 3
作者:csdn博客 Spike_King