Basic knowledge of C++ STL

  • STL (Standard Template Library, standard template library)
  • Broadly divided into: container (container), algorithm (algorithm), iterator (iterator). Containers and algorithms are connected through iterators.
  • Almost all code in STL uses class templates or function templates

 

Containers, Algorithms, Iterators in STL

 

 

Vector container

#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 stores custom data types

#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;
}

container nested container

	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;
	}

Guess you like

Origin blog.csdn.net/MWooooo/article/details/126643738