vector访问元素(删除性访问)
程序员文章站
2022-03-01 23:21:21
...
#include <cstdio>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
vector<int> vec1;
vector<int> vec2;
vector<int> vec3;
vec1.clear();
vec2.clear();
vec3.clear();
int a[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
for(int i = 0; i < 10; i++)
{
vec1.push_back(a[i]);
vec2.push_back(a[i]);
vec3.push_back(a[i]);
}
///用这种删除性访问时(如若不反转)vector相当于stack先进后出
///因为删除操作,只能从后面删除
while(!vec1.empty())
{
cout << vec1.back() << " ";
vec1.pop_back();
}
cout << '\n' << "-------------------" << '\n';
reverse(vec2.begin(), vec2.end());
while(!vec2.empty())
{
cout << vec2.back() << " ";
vec2.pop_back();
}
cout << '\n' << "-------------------" << '\n';
/// while(!vec3.empty())
/// {
/// cout << vec3.front() << " ";
/// vec3.pop_front();此处编译不通过,vector没有pop_front成员
/// }
return 0;
}