C++ STL基础知识

  • STL(Standard Template Library,标准模板库)
  • 广义上分为:容器(container),算法(algorithm),迭代器(iterator)。容器和算法之间通过迭代器进行连接。
  • STL中几乎所有代码均采用了类模板或者函数模板

 

STL中容器、算法、迭代器

 

 

Vector容器

#include <vector>
#include <algorithm>  //标准算法头文件
using namespace std;


void kPrint(int i)
{
	cout << i << endl;
}

int main()
{
	vector<int> v;
	v.push_back(0);   //push_back尾插法为容器插入数据
	v.push_back(10);
	v.push_back(20);
	v.push_back(30);
	v.push_back(40);

	//需求:遍历打印
	//1. for循环打印
	for (vector<int>::iterator itbegin = v.begin(); itbegin != v.end(); ++itbegin)
	{
		cout << *itbegin << endl;
	}

	//2. while循环打印
	vector<int>::iterator itbegin = v.begin();//起始迭代器,指向容器中第一个元素的位置
	vector<int>::iterator itend = v.end();//结束迭代器,指向容器中最后一个元素的下一个位置
	while (itbegin != itend)
	{
		cout << *itbegin << endl;
		++itbegin;
	}

	//3. for_each算法遍历
	vector<int>::iterator itbegin = v.begin();//起始迭代器,指向容器中第一个元素的位置
	vector<int>::iterator itend = v.end();//结束迭代器,指向容器中最后一个元素的下一个位置
	for_each(itbegin, itend, kPrint);

	system("pause");
	return 0;
}

vector存放自定义数据类型

#include "test1.h"
#include "iostream"
#include "string"
#include <vector>
#include <algorithm>  //标准算法头文件
using namespace std;

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

	string m_name;
	int m_age;
};

void test01()
{
	Person p1("Tom", 8);
	Person p2("Jerry", 10);
	Person p3("Katty", 9);
	Person p4("Sophia", 5);

	vector<Person> p;
	p.push_back(p1);
	p.push_back(p2);
	p.push_back(p3);
	p.push_back(p4);

	for (vector<Person>::iterator i = p.begin(); i!=p.end(); i++)
	{
		cout << "name: " << i->m_name << " age: " << i->m_age << endl;
	}

}


int main()
{
	test01();

	system("pause");
	return 0;
}

容器嵌套容器

	vector<int> v1;
	vector<int> v2;
	vector<int> v3;
	for (int i = 0; i<3; ++i)
	{
		v1.push_back(i);
		v2.push_back(i * i);
		v3.push_back(i * i *i);
	}

	vector<vector<int>> v;
	v.push_back(v1);
	v.push_back(v2);
	v.push_back(v3);

	for (vector<vector<int>>::iterator vi = v.begin(); vi != v.end(); vi++)
	{
		for (vector<int>::iterator vti = (*vi).begin(); vti != (*vi).end(); vti++)
		{
			cout << *vti << " ";
		}
		cout << endl;
	}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值