ベクトルコンテナの単純なケース

 test01()のコンテナにint型を入れます

test02()のコンテナにクラスオブジェクトを配置します

test03()のコンテナにクラスオブジェクトポインタを置きます

コンテナはtest04()にネストされています。

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;

class Person{
public:
	Person(string name,int age)
	{
		this->name = name;
		this->age = age;
	}
	string name;
	int age;
};

void myPrint(Person p)	//回调函数
{
	cout<<"姓名:"<< p.name << "年龄:"<< p.age <<endl;
}

void myPrintPerson(int v)	//回调函数
{
	cout<<v<<endl;
}
void test01()
{
	vector<int> v;
	v.push_back(1);
	v.push_back(2);
	v.push_back(3);
	//遍历方法一
	vector<int>::iterator begin = v.begin();
	vector<int>::iterator end = v.end();
	while(begin!=end)
	{
		cout<<*(begin++)<<endl;
	}
	//遍历方法2
	for(vector<int>::iterator it = v.begin();it!=v.end();it++)
	{
		cout<<*it<<endl;
	}
	//遍历方法3
	for_each(v.begin(),v.end(),myPrintPerson);
}

void test02()
{
	vector<Person> v;
	Person p1("test01",11);
	Person p2("test02",12);
	Person p3("test03",13);
	v.push_back(p1);
	v.push_back(p2);
	v.push_back(p3);
	for(vector<Person>::iterator it = v.begin();it!=v.end();it++)
	{
		cout<<"姓名:"<< (*it).name << "年龄:"<< (*it).age <<endl;
	}
	//遍历方法3
	for_each(v.begin(),v.end(),myPrint);   //可以查看一下for_each函数定义
}

void test03()
{
	vector<Person*> v;
	Person p1("test01",11);
	Person p2("test02",12);
	Person p3("test03",13);
	v.push_back(&p1);
	v.push_back(&p2);
	v.push_back(&p3);
	for(vector<Person*>::iterator it = v.begin();it!=v.end();it++)
	{
		cout<<"姓名:"<< (*it)->name << "年龄:"<< (*it)->age <<endl;
	}
}

void test04()
{
	int i;
	/*容器嵌套容器*/
	vector<vector<int>> v;
	vector<int> v1;
	vector<int> v2;
	vector<int> v3;
	for(i=0; i < 3; i++)
	{
		v1.push_back(i);
		v2.push_back(i+10);
		v3.push_back(i+100);
	}
	v.push_back(v1);
	v.push_back(v2);
	v.push_back(v3);

	for(vector<vector<int>>::iterator it = v.begin();it!=v.end();it++)
	{
		for(vector<int>::iterator vit = (*it).begin();vit!=(*it).end();vit++)
		{
			cout<<*vit<<' ' ;
		}
		cout<<endl;

	}

}

int main()
{
	//test01();	
	//test02();
	//test03();
	test04();
	return 0;
}

 

おすすめ

転載: blog.csdn.net/weixin_42596333/article/details/112981925