vector存放默认数据类型,自定义数据类型,vector嵌套vector,并遍历输出

目录

遍历输出的方法:

<默认数据>

<自定义数据>

嵌套vector>


遍历输出的方法:

1、使用for循环输出

2、调用for_each()函数 // 需要添加头文件#include <algorithm>

<默认数据>

#include <iostream>
using namespace std;
#include <vector>
#include <algorithm>/*algorithm意为"算法",是C++的标准模版库(STL)中最重要的头文件之一,提供                        
                      了大量基于迭代器的非成员模版函数*/


void myprint(int temp)
{
	cout << temp << endl;
}
int main()
{
	vector<int> sys;
	sys.push_back(001);
	sys.push_back(004); 
	sys.push_back(003);
	sys.push_back(002);


//第一种,推荐
	for (vector<int>::iterator bg = sys.begin(); bg != sys.end(); bg++)
	{
		cout << *bg<<endl;
	}
//第二种,也行,本质也是for循环
	for_each(sys.begin(), sys.end(), myprint);

	return 0;
}

<自定义数据>

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

class person
{
public:
	person(string name, int age)
	{
		this->m_name = name;
		this->m_age = age;
	}
	string m_name;
	int m_age;
};
void text001()
{
	vector<person>v;

	person p1("aaa", 1);
	person p2("bbb", 2);
	person p3("ccc", 3);
	person p4("ddd", 4);
	person p5("eee", 5);

	v.push_back(p1);
	v.push_back(p2);
	v.push_back(p3);
	v.push_back(p4);
	v.push_back(p5);

	for (vector<person>::iterator it = v.begin(); it != v.end(); ++it)
	{
		cout << (*it).m_name << "  " << (*it).m_age << endl;
		cout << it->m_name << "  " << it->m_age << endl;
	}
}
void text002()
{
	vector<person*>v;

	person p1("aaa", 1);
	person p2("bbb", 2);
	person p3("ccc", 3);
	person p4("ddd", 4);
	person p5("eee", 5);

	v.push_back(&p1);
	v.push_back(&p2);
	v.push_back(&p3);
	v.push_back(&p4);
	v.push_back(&p5);

	for (vector<person*>::iterator it = v.begin(); it != v.end(); ++it)
	{
		cout << (**it).m_name << "     " << (**it).m_age << endl;
		cout << (*it)->m_name << "     " << (*it)->m_age << endl;
	}
}
int main()
{
	text001();
	text002();


	return 0;
}

*it 指代 “ <> ”中的类型,it可以简单的理解为指针(早期);

<vector嵌套vector>

别把自己套进去就行

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


int main()
{
	vector<vector<int>>v;
	vector<int>v1;
	vector<int>v2;
	vector<int>v3;
	vector<int>v4;

	for (int i = 0; i < 5; i++)
	{
		v1.push_back(i + 1);
		v2.push_back(i + 2);
		v3.push_back(i + 3);
		v4.push_back(i + 4);
	}
	v.push_back(v1);
	v.push_back(v2);
	v.push_back(v3);
	v.push_back(v4);

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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值