在开始Effective STL系列之前,有必要对STL基础进行一个全面的基础学习。
学习链接地址如下:
http://wenku.baidu.com/link?url=i6SBAotuThXbBw3Nx7pSyg84zPdVQC6m0chFzuC3DZzhlGgJcxiblzpGijIO9_u4GRbkqm9_1pDnUero8tDNJKJTl_45ZBKg6OFz89gkc67
- STL抽象的是什么?
有些算法并不依赖于数据结构的特定实现,而只是依赖于该结构的几个基本的语义属性,STL抽象出这些基本属性,成功的将算法与数据结构分离,在没有效率损失的前提下,得到了极大的弹性。
如下代码:
vector<int> ivec;
deque<int> ideque;
//一个泛型的排序算法
sort(ivec.begin(),ivec.end());
sort(ideque.begin(),ideque.end());
用一个泛型算法可以处理多种数据结构。而且在获得弹性的同时运行效率上和以前相比没有损失。
- STL的6大组件:
容器(Container)
算法(Algorithm)
迭代器(Iteratior)
仿函数(Function Object)或者称为函数对象
适配器(Adapter)
空间配制器(Allocator)
STL的组成:
STL组件 | 程序需要的头文件 |
---|---|
Algorithms | <algorithm> |
四个数值相关的算法 | <numberic> |
vector | <vector> |
list | <deque> |
stack | <stack> |
queue | <queue> |
priority queue | <queue> |
map | <map> |
set | <set> |
multimap | <map> |
multiset | <set> |
function objects | <functional> |
iterator adapter | <iterator> |
一个小程序:
template<typename T>
void print_elements(T elem)
{
cout<<elem<<" ";
}
int void main()
{
void(*pfi)(int) = print_elements;
list<int> lists;
lists.push_back(10);
lists.push_back(20);
bool flag = lastGreatThanFirst(lists);
map<string,double> maps;
string s = "sdwe";
cout<<s;
int ia[7] = {0,1,2,3,4,5,6};
list<int> ilist(ia,ia+7);// 因为ia也是一个迭代器,一个指针的迭代器。这个构造函数是设置了迭代器的起始和结束位置
for_each(ilist.begin(),ilist.end(),pfi);
ilist.push_back(7);
ilist.push_back(0);
ilist.push_back(7);
ilist.push_back(9);
for_each(ilist.begin(),ilist.end(),pfi);
ilist.remove_if(bind2nd(modulus<int>(),2));//去除所有奇数
for_each(ilist.begin(),ilist.end(),pfi);
}
命名空间的两种使用方式:
using Rewind::i;//这是一个using declaration,他使I成为当前范围内代表Rewind::i的同义词。
using namespace Rewind;//这是一个using directive,它使Renwind内的所有名字曝光。
using namepace会再度引发名称冲突:
namespace Renwind
{
int i=10;
void myGlobalFcunc();
}
main函数
{
using namespace Renwind;
int i = 1;
cout<<i<<endl;
}
- 类模板显示特化
#include <iostream>
template<typename T>
class CTest{
public:
void operator()(){ std::cout<<"CTEST<T>"<<std::endl; }
};
//类显化
template<>
class CTest<int>{
public:
void operator()(){
using namespace std;
std::cout<<"CTEST<int>"<<std::endl;
}
};
template<typename T>
void printData(T elem)
{
cout>>elem>>endl;
}
//函数显化
template<>
void printData(int a)
{
std::cout<<"this is the int method"<<std::endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
CTest<double> d;
d();
CTest<int> i;
i();
printData<int>(12);
getchar();
return 0;
}
- 关键字 typename
作为类型前的标志符号:
template<typename T>
class MyClass
typename T::SubType *ptr;
指出SubType是T中定义的一个类型,因此ptr是一个指向T::SubType的指针,如果不加typename,表达式被认为是T中的静态成员SubTyp和ptr的乘积。