vector删除指定索引的元素
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
std::vector<int> v;
v.push_back(0);
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
v.push_back(5);
v.push_back(6);
v.push_back(7);
v.push_back(8);
v.push_back(9);

unsigned int j = 0;
int size = v.size();
for(unsigned int i=0; i< size; i++)
{
if(i%2 == 0)
{
v.erase(v.begin() + i - j);
j++;
}
}
cout << "after remove"<< endl ;
for(unsigned int i=0; i < v.size(); i++)
cout << v[i] <<" ";

结果是 1 3 5 7 9


常见iterator自增,如果多增加,可能报错

1
2
3
4
5
6
7
8
9
10
11
12
std::vector<int> v;
v.push_back(0);
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);

for(vector<int>::iterator it=v.begin(); it != v.end(); it++)
{
it = it + 5;
cout << *it << endl;
}

这样的程序是错的,会越界。 应该改成这样
1
2
3
4
5
6
for(vector<int>::iterator it=v.begin(); it != v.end(); it++)
{
int step = v.end() - it;
it = it+step/5;
cout << *it << endl;
}