#include <vector>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
using namespace std;
int main(int argc, char* argv[])
{
std::vector<int> test_vec;
for(int i = 0 ;i < 10;i++)
test_vec.push_back(i);
for(std::vector<int>::iterator itor = test_vec.begin();itor!=test_vec.end();itor++)
{
printf("node = %d\n" ,*itor);
}
printf("node size = %d\n" ,test_vec.size());
getchar();
return 0;
}
输出如下:
node = 0
node = 1
node = 2
node = 3
node = 4
node = 5
node = 6
node = 7
node = 8
node = 9
node size = 10
现在我们要在迭代的时候进行删除其中某个元素
#include <vector>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
using namespace std;
int main(int argc, char* argv[])
{
std::vector<int> test_vec;
for(int i = 0 ;i < 10;i++)
test_vec.push_back(i);
for(std::vector<int>::iterator itor = test_vec.begin();itor!=test_vec.end();itor++)
{
printf("node = %d\n" ,*itor);
if(*itor == 2)
{
test_vec.erase(itor);
}
}
printf("node size = %d\n" ,test_vec.size());
getchar();
return 0;
}
输出如下:
node = 0
node = 1
node = 2
node = 4
node = 5
node = 6
node = 7
node = 8
node = 9
node size = 9
比较意外,3居然没遍历到????
接下来是正确的代码
#include <vector>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
using namespace std;
int main(int argc, char* argv[])
{
std::vector<int> test_vec;
for(int i = 0 ;i < 10;i++)
test_vec.push_back(i);
for(std::vector<int>::iterator itor = test_vec.begin();itor!=test_vec.end();)
{
printf("node = %d\n" ,*itor);
if(*itor == 2)
{
itor =test_vec.erase(itor);
}
else
{
itor++;
}
}
printf("node size = %d\n" ,test_vec.size());
getchar();
return 0;
}
输出:
node = 0
node = 1
node = 2
node = 3
node = 4
node = 5
node = 6
node = 7
node = 8
node = 9
node size = 9
使用vector的erase函数,记
住,该函数是迭代器失效,返回下一个迭代器
。