vector容器1(添加元素,遍历元素)
#include <iostream> using namespace std; #include <vector> int main() { vector<int> v1; cout<<"length:"<<v1.size()<<endl; v1.push_back(1); v1.push_back(3); v1.push_back(5); cout<<"length:"<<v1.size()<<endl; cout<<"头部元素:"<<v1.front()<<endl; //修改头部元素的值 //函数返回值当左值,应该返回一个引用 v1.front()=11; v1.back()=55; while(v1.size()>0) { cout<<"尾部元素:"<<v1.back()<<endl;//获取尾部元素 v1.pop_back();//删除尾部元素 } system("pause"); return 0; }
程序运行结果:
//使用迭代器遍历vector
//迭代器遍历
int main() { vector<int> v1(10); for(int i=0;i<10;i++) { v1[i]=i+1; } for(vector<int>::iterator it=v1.begin();it!=v1.end();it++) //it=v1.begin()迭代器指向vector的开头 { cout<<*it<<" "; } return 0; }