vector 用法及代码代码示例
vector 用法及代码代码示例
1. 删除特定的元素
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int values1[10] = {1, 2, 0, 3, 4, 5, 0};
vector<int> values4(values1, values1 + 7);
for (auto iter = values4.begin(); iter != values4.end();)
{
if (*iter == 0)
iter = values4.erase(iter); // erase方法可以返回下一个有效的iterator
else
iter++;
}
return 0;
}
1. 删除范围内的元素
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> myvector{ 1, 2, 3, 4, 5 };
vector<int>::iterator it1, it2;
it1 = myvector.begin();
it2 = myvector.end();
it2--;
it2--;
myvector.erase(it1, it2);
for (auto it = myvector.begin(); it != myvector.end(); ++it)
cout << ' ' << *it;
return 0;
}
输出:
4 5