C++STL初识 学习笔记

一.STL六大组件
1.容器:各种数据结构,如vector、list、deque、set、map等
2.算法:各种常用的算法,如sort、find、copy等
3.迭代器:容器与算法间的胶合剂
4.仿函数:行为类似函数,可作为算法的某种策略
5.适配器:一种用来修饰容器或者仿函数或迭代器接口的东西
6.空间配置器:负责空间的配置与管理

二.vector存放内置数据类型
容器:vector
算法:for_each
迭代器:vector::iterator

#include 
#include
#include
#include
#include//标准算法头文件
using namespace std;

void myPrint(int val) {
	cout << val << endl;
}

void test01() {
	//
	vector<int> v;
	//向容器中插入数据
	v.push_back(10);
	v.push_back(20);
	v.push_back(30);
	v.push_back(40);
	//通过迭代器访问容器中的数据
	vector<int>::iterator itBegin = v.begin();//指向容器中第一个元素
	vector<int>::iterator itEnd = v.end();//指向最后一个元素
	//第一种遍历方式
	while (itBegin != itEnd) {
		cout << *itBegin << endl;
		itBegin++;
	}
	//第二种遍历方式
	for (vector<int>::iterator it = v.begin(); it != v.end(); it++) {
		cout << *it << endl;
	}
	//第三种方式,使用STL提供的算法
	for_each(v.begin(), v.end(), myPrint);
}
int main()
{
	test01();
	system("pause");
	return 0;
}

三.vector存放自定义数据类型

#include 
#include
#include
#include
#include//标准算法头文件
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() {
	vector<Person>v;
	Person p1("aaa", 10);
	Person p2("bbb", 20);
	Person p3("ccc", 30);
	Person p4("ddd", 40);
	Person p5("eee", 50);
	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 << "name:" << (*it).m_Name << "age:" << (*it).m_Age << endl;
	}
}

void test02() {
	vector<Person*>v;
	Person p1("aaa", 10);
	Person p2("bbb", 20);
	Person p3("ccc", 30);
	Person p4("ddd", 40);
	Person p5("eee", 50);
	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 << "name:" << (*it)->m_Name << "age:" << (*it)->m_Age << endl;
	}
}

int main()
{
	test01();
	test02();
	system("pause");
	return 0;
}

四.容器嵌套容器

#include 
#include
#include
#include//标准算法头文件
using namespace std;
void test01() {
	vector<vector<int>> v;
	vector<int> v1;
	vector<int> v2;
	vector<int> v3;
	vector<int> v4;
	for (int i = 0; i < 4; 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++) {
		for (vector<int>::iterator vit = (*it).begin(); vit != (*it).end(); vit++) {
			cout << *vit << "";
		}
	}
}
int main()
{
	test01();	
	system("pause");
	return 0;
}

你可能感兴趣的:(C++)