3

vector删除指定索引的元素

 1 year ago
source link: https://charon-cheung.github.io/2023/07/20/C++/C++%20%20%E6%A8%A1%E6%9D%BF%E4%B8%8ESTL/vector%E5%88%A0%E9%99%A4%E6%8C%87%E5%AE%9A%E7%B4%A2%E5%BC%95%E7%9A%84%E5%85%83%E7%B4%A0/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

vector删除指定索引的元素 | 沉默杀手

vector删除指定索引的元素
2023-07-20|C++C++ 模板与STL|
Word count: 213|Reading time: 1 min
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自增,如果多增加,可能报错

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;
}

这样的程序是错的,会越界。 应该改成这样
for(vector<int>::iterator it=v.begin(); it != v.end(); it++)
{
int step = v.end() - it;
it = it+step/5;
cout << *it << endl;
}
©2018 - 2023 By Charon Cheung
Driven - Hexo|Theme - Melody

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK