#include<iostream>#include<string>#include<vector>#include<algorithm>usingnamespace std;//手写遍历过程voidtest1(void){//创建一个vector容器vector<int> v;//向容器中插入数据v.push_back(10);//尾插法v.push_back(20);//通过迭代器访问容器中的数据for(vector<int>::iterator vi = v.begin(); vi != v.end(); vi++){cout <<*vi << endl;}}//采用STL标准库voidMyprint(int val){cout<< val << endl;}voidtest2(void){vector<int> v;v.push_back(20);v.push_back(21);for_each(v.begin(), v.end(), Myprint);//回调技术}intmain(){test1();test2();return0;}
存放自定义数据类型
#include<iostream>#include<string>#include<vector>#include<algorithm>usingnamespace std;classPerson{public:Person(string name,int age){this->m_age = age;this->m_name = name;}string m_name;int m_age;};voidtest1(void){vector<Person*> v_p;Person p1("p1",10);Person p2("p2",20);v_p.push_back(&p1);v_p.push_back(&p2);for(vector<Person*>::iterator it= v_p.begin(); it != v_p.end(); it++){cout <<"my name is "<<(*it)->m_name <<" my age is "<<(*it)->m_age << endl;}}intmain(){test1();return0;}