您的位置:首页 > 编程语言 > C语言/C++

c++模版学习

2012-09-26 10:17 176 查看
#include <iostream>

using namespace std;

#include <typeinfo>

#include <string>

template <typename T=int,int value=10>//可以初始化模版

class Type

{

T a;

int val;

public:

Type():val(value)

{

}

T getA()

{

return a;

}

int getval()

{

return this->val;

}

};

template<>//全特化

class Type<int,10>

{

static int a;

public:

int getA()

{

cout<<"int"<<endl;

return a;

}

};

int Type<int,10>::a=10;

//模版函数

template<typename T>

string getType(T t)

{

return typeid(T).name();

}

int main()

{

Type<double,19> b;

cout<<b.getval()<<endl;

cout<<getType(10)<<endl;

return 0;

}

标准模版

/*标准容器(类模板)的共性:vector,deque,list,set/map,multi...

构造函数:无参构造,拷贝构造,区间构造(两个迭代器表示的两个位置)

析构:

迭代器相关:正向.begin(),.end(),反向.rbegin(),.rend()

iterator,reverse_iterator,const_iterator,const_reverse_iterator

*,->,=,++,==,!= --

插入:.insert(pos,element),其中pos表示插入位置,是个迭代器

删除:.erase(pos), .erase(pos_beg, pos_end)

清除:.clear()

大小:.size(), .max_size(), .empty()

交换:.swap(c2), swap(c1,c2)

运算符:=, >, <, >=, <=, ==, !=

*/

/*序列式容器的共性:vector,deque,list

构造函数:指定元素个数和初始值(初始值默认为零初始化)

插入:.insert(pos, n, element), .insert(pos, pos_beg, pos_end)

赋值:.assign(n, element), .assign(pos_beg, pos_end)

调整:.resize(n, element=零初始化)

首尾:.front(), .back()

增删:.push_back(element), .pop_back()只删除,返回void

*/

/*vector的个性:

当前容量: .capacity()

约定容量: .reserve(n)

下标[]: .operator[](i)不检查越界, .at(i)越界抛出异常

*/

/*deque的个性:double-ended queue

下标[]: .operator[](i)不检查越界, .at(i)越界抛异常

增删:.push_front(element), .pop_front()

*/

/*list的个性:双向链表

增删:.push_front(element), .pop_front(), .remove(element)//==

不支持下标[]

除重:.unique()相邻的重复元素只保留一个

排序:.sort(compare_func=less)默认用小于符号比较,从小到大排序

倒置:.reverse()颠倒链表中元素顺序

转移:.splice(pos,list2), .splice(pos,list2,pos2), .splice(pos,list2,pos_beg,pos_end)

归并:.merge(list2)

*/

/*关联式容器共性:都是用二叉查找树实现的,都自动根据关键字排序

set<K>, multiset<K>, map<K,V>, multimap<K,V)

查找:.find(key)返回一个迭代器指向找到的第一个元素,失败返回.end()

统计:.count(key)统计关键字等于key的元素的个数

删除:.erase(key)删除关键字等于key的所有元素

区间:.lower_bound(key)取得关键字为key的第一个元素的位置, .upper_bound(key)取得关键字为key的最后一个元素之后的位置, .equal_range(key)一次取得关键字为key的元素的区间,返回一个pair

插入:.insert(element)

*/

/*关联式容器共性:都是用二叉查找树实现的,都自动根据关键字排序

set<K>, multiset<K>, map<K,V>, multimap<K,V)

查找:.find(key)返回一个迭代器指向找到的第一个元素,失败返回.end()

统计:.count(key)统计关键字等于key的元素的个数

删除:.erase(key)删除关键字等于key的所有元素

区间:.lower_bound(key)取得关键字为key的第一个元素的位置, .upper_bound(key)取得关键字为key的最后一个元素之后的位置, .equal_range(key)一次取得关键字为key的元素的区间,返回一个pair

插入:.insert(element)

构造函数:可以用比较函数作为参数bool(*compare)(K a,K b)

*/

/*map的个性:

不允许key重复

元素是key/value对

支持以key为下标访问对应的value的引用,如果key不存在就新增一个元素以这个为key。

*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: