STL (Standard Template Library)

STL的基本组件:

** 容器(container)

** 迭代器(iterator)

** 函数对象(function object)

**   算法(algorithm)

容器:

** 容纳, 包含一组元素的对象

** 基本容器类模板

   * 顺序容器: array, vector, dequeue, forward_list, list

   * 关联容器(有序): set, multiset, map, multimap

   * 无序关联容器: unprdered_set, unordered_multiset, unordered_map, unorder_multimap

迭代器:

** 提供了顺序访问容器中每个元素的方法

** 可以使用“++” 运算符来获得指向下一个元素的迭代器

** 可以使用“*” 运算符来访问迭代器所指向的元素,如果元素类型是类或结构体,还可以使用“->”

     运算符直接访问该元素的一个成员

** 有些迭代器还支持通过“--” 运算符获得指向上一个元素的迭代器;

** 迭代器是泛化的指针: 指针也具有同样的特心烦,因此指针本身就是一种迭代器

** 使用独立于STL容器的迭代器,需要包含头文件<iterator>

函数对象:

使用STL的函数对象,需要包含头文件<functional>

算法:

使用STL的算法,需要包含头文件<algorithm>

例子:将一个vector里面的元素的相反数输出出来:

#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <functional>

using namespace std;

int main(){
	const int N = 5;
	vector <int> s(N); //container
	for (int i = 0; i < N; i++){
		cin >> s[i];
	}
	// transform() is an algorithm
	// s.begin(), s.end(), ostream_iterator are iterator
	// negate is function object aims to calculate the opposite number
	transform(s.begin(), s.end(), ostream_iterator<int>(cout, " "),negate<int>());
	cout<<endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_42380877/article/details/81156734