一、概述
案例:练习vector容器(基本数据类型、自定义类型、容器嵌套容器),并输出vector容器中的内容
开发工具:sublinetext
二、示例图片
三、示例代码
#include <iostream> #include <vector> #include <string> #include <algorithm>//标准算法头文件 using namespace std; //原生指针也是迭代器 void test1(){ int arr[5] = {1,2,3,4,5}; int *p = arr; for(int i=0;i<5;i++){ //此处P++代表地址+1,用*取值 cout << "p:"<<*(p++)<<endl; } } void myPrint(int val){ cout <<val<<endl; } /** * 测试vector * */ void test2(){ vector<int> v;//创建vector容器,容器中存放的内容为int类型 //插入元素 v.push_back(10); v.push_back(30); v.push_back(20); //遍历元素 vector<int>::iterator itBegin = v.begin();//v.begin()起始迭代器,指向容器中第一个数据 vector<int>::iterator itEnd = v.end();//v.end()结束迭代器,指向容器中最后一个元素的下一个位置 cout<< "第一种遍历方式:"<<endl; while(itBegin!=itEnd){ cout<<*itBegin<<endl; itBegin++; } cout<<"第二种遍历方式:"<<endl; for(vector<int>::iterator it = v.begin();it!=v.end();it++){ cout << *it<<endl; } cout<< "第三种遍历"<<endl; for_each(v.begin(),v.end(),myPrint); } //自定义数据类型 class Person{ public: string m_name; int m_age; Person(string name,int age){ this->m_name = name; this->m_age = age; } }; void test3(){ vector<Person> v; Person p1("tony",30); Person p2("luoluoyang",3); Person p3("kiki",18); v.push_back(p1); v.push_back(p2); v.push_back(p3); for(vector<Person>::iterator it=v.begin();it!=v.end();it++){ cout << "name:"<<it->m_name<<",age:"<<it->m_age<<endl; } } //存放自定义数据类型指针 void test4(){ vector<Person*> v; Person p1("tony",30); Person p2("luoluoyang",3); Person p3("kiki",18); v.push_back(&p1); v.push_back(&p2); v.push_back(&p3); for(vector<Person*>::iterator it=v.begin();it!=v.end();it++){ cout<< "name:"<<(*it)->m_name<<", age:"<<(*it)->m_age<<endl; } } //容器嵌套容器 void test5(){ vector<vector<Person>> vv; vector<Person> v1; vector<Person> v2; vector<Person> v3; //添加数据 Person p1("tony",30); Person p2("luoluoyang",3); Person p3("kiki",18); //将内容放入容器 v1.push_back(p1); v2.push_back(p2); v3.push_back(p3); //将小容器放入大容器内 vv.push_back(v1); vv.push_back(v2); vv.push_back(v3); //输出容器内容 for(vector<vector<Person>>::iterator its = vv.begin();its!=vv.end();its++){ for(vector<Person>::iterator it = its->begin();it!=its->end();it++){ cout<< "name:"<<it->m_name<<", age:"<<it->m_age<<endl; } } } /** * 程序的入口main方法 * */ int main(int argc, char const *argv[]) { // test1(); // test2(); // test3(); // test4(); test5(); return 0; }