搜索
您的当前位置:首页正文

C++(STL)学习(一)

来源:步旅网

基本概念

STL(标准模板库)
STL从广义上分为:容器、算法、迭代器,容器和算法之间通过迭代器进行无缝链接。
STL六大组件:容器、算法、迭代器、仿函数、适配器、空间配置器
容器:各种数据结构(类模板)
算法:各种常用的算法(函数模板)
迭代器:所有的容器都有自己的迭代器

容器

序列式容器
关联式容器

算法

质变算法:运算过程中改变区间内的元素的内容,例如拷贝,替换,删除等
非质变算法:运算过程中不会改变区间内的元素的内容,例如查找、计数、遍历等

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

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



//  普通指针也是属于一种迭代器
void test01()
{
	int arr[5] = { 1,2,3,4,5 };
	int *p = arr;
	for (int i = 0; i < 5; i++)
	{
		//	cout << arr[i] << endl;
		cout << *p++ << endl;
	} 
}

void test02()
{
	vector<int>v;
	v.push_back(10);
	v.push_back(20);
	v.push_back(30);
	v.push_back(40);

	//  遍历1
	/*vector<int>::iterator itBegin = v.begin();

	vector<int>::iterator itEnd = v.end();  //  指向最后一个元素的下一个位置

	while (itBegin != itEnd)
	{
		cout << *itBegin << endl;
		itBegin++;
	}*/

	//  遍历2
	/*for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
	{
		cout << *it << endl;
	}*/

	//  遍历3
	for_each(v.begin(), v.end(), MyPrint);

}

//  自定义数据类型

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

	string m_name;
	int m_age;
};


void test03()
{
	/*vector<Person>v;
	Person p1("aaaa", 10);
	Person p2("bbbb", 20);
	Person p3("cccc", 30);
	Person p4("dddd", 40);

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

	//  遍历
	for (vector<Person>::iterator it = v.begin(); it != v.end(); it++)
	{
		cout << (*it).m_name;
		cout << it->m_age << endl;
	}*/

	vector<Person *>v;
	Person p1("aaaa", 10);
	Person p2("bbbb", 20);
	Person p3("cccc", 30);
	Person p4("dddd", 40);

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

	//  遍历
	for (vector<Person *>::iterator it = v.begin(); it != v.end(); it++)
	{
		cout << (**it).m_name;
		cout << (*it)->m_age << endl;
	}



}


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

因篇幅问题不能全部显示,请点此查看更多更全内容

Top