C++ STL 總結

資料地址:http://blog.chinaunix.net/uid-24219701-id-2181266.html


一、簡介

  STLStandard Template Library,標準模板庫)是惠普實驗室開發的一系列軟件的統稱。

 STL的代碼從廣義上講分爲三類:algorithm(算法)、container(容器)和iterator(迭代器)。

 容器:是可容納一些數據的模板類;

 算法:就是處理容器裏面數據的方法、操作;

迭代器:遍歷容器中數據的對象(它將算法和容器連在一起)。


二、容器實例

1)list,vectordeque- - 隊列容器;

2)setmultisets,map,multimaps - - 關聯容器;


1. 向量(vector)

1)初始化實例

<span style="font-size:14px;">//vector初始化實例
#include "stdafx.h"
#include <iostream>
#include <vector>

using namespace std;

int ar[10] = {12, 45, 234, 64, 12, 35, 63, 23, 12, 55};
char* str = "Hello World";

int _tmain(int argc, _TCHAR* argv[])
{
	vector<int> vec1(ar, ar+10);
	vector<char> vec2(str, str+strlen(str));

	cout << "vec1:";
	for (vector<int>::const_iterator p1 = vec1.begin(); p1 != vec1.end(); ++p1)
		cout << *p1; 
	//&表示取地址,是取地址;
	//*是指針,是取地址的內容;

	cout << '\n' << "vec2:";
	for (vector<char>::const_iterator p2 = vec2.begin(); p2 != vec2.end(); ++p2)
		cout << *p2;

	cout << '\n';

	system("PAUSE");
	return 0;
}</span>

2)操作實例

//vector操作實例
#include "stdafx.h"
#include <iostream>
#include <vector>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
	vector<int> vec1;
	vector<int> vec2(10, 6);
	vector<int> vec3(vec2.begin(), vec2.begin() + 3);

	vector<int>::iterator i;

	//按順序顯示vec1
	cout << "vec1.begin() ~ vec1.end():"<<'\n';
	for (i = vec1.begin(); i != vec1.end(); ++i)
		cout << *i << " ";
	cout << endl;

	vec1.push_back(2); //在最後添加一成員
	vec1.push_back(4);
	vec1.insert(vec1.begin()+1, 5);//在vector第1+1個位置上插入"5"
	vec1.insert(vec1.begin()+1, vec3.begin(), vec3.end());

	cout << "after push and insert,vec1 is :"<<'\n';
	for (i = vec1.begin(); i != vec1.end(); ++i)
		cout << *i << " ";
	cout << endl;

	vec2.assign(8, 1); //重新給vec2賦值,8個成員初始值都爲1(全部重新賦值)
	cout << "vec2.assign(8,1) is :" << '\n';
	for (i = vec2.begin(); i != vec2.end(); ++i)
		cout << *i << " ";
	cout << endl;

	cout << "vec1.front() is :" << vec1.front() << endl;
	cout << "vec1.back() is :" << vec1.back() << endl;
	cout << "vec1.at(4) is :" << vec1.at(4) << endl;  //和數組類似,實際是第5個
	cout << "vec1[4] is:" << vec1[4] << endl;

	vec1.pop_back();
	vec1.erase(vec1.begin()+1, vec1.end()-2);
	cout << "after pop and erase(vec1.begin()+1, vec1.end()-2),vec1 is :" << '\n';
	for (i = vec1.begin(); i != vec1.end(); ++i)
		cout << *i << " ";
	cout << endl;

	//vec1.size();
	//vec1.empty();

	system("PAUSE");
	return 0;
}

待續。。



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章