1、面对 reference 的所有操作都和面对 “ reference 所代表的对象” 所进行的操作一般无二。
2、pointer 参数与 reference 参数之间一个重要差异是:
pointer 可能(也可能不)指向某个实际对象。当我们提领 pointer 时,一定要注意先确定其值并非为0.至于 reference ,则必定会代表某个对象,所以不用做此检查。
3、函数模板以关键字 template 开场,其后紧接着以成对尖括号(<>)包围起来的一个或多个标识符。这些标识符用以表示我们希望推迟决定的数据类型。
template <typename Type>
关键字 typename 表示 Type 在模板函数中是一个暂时放置类型的占位符,Type 是个任意名称,在模板函数实例中确定具体类型。
4、定义一个数组存放函数指针const vector< int >* (*seq_array[])( int ) = {
fibon_seq, lucas_seq, pell_seq,
triang_seq, square_seq, pent_seq
};
函数指针指向形参为 int,返回类型为 const vector< int >* 的函数。
5、inline 函数定义。为了能够扩展 inline 函数的内容,在每个调用点上,编译器都得取得其定义。这意味着我们必须将 inline 函数的定义放在文件中而不是把它放在不同的程序代码文件中。
6、Function Object. 所谓Function Object,是某种class的实例对象,这种类class对function call运算符()做了重载操作,如此一来可使function object被当成一般函数来使用。
function object实现了原本需要以独立函数加以定义的事物,主要是使效率变高,可以令call运算符成为inline,从而消除“通过函数指针来调用函数”时需付出的额外代价。
标准库中定义了一组function object,分为算术运算(arithmetic)、关系运算(relational)和逻辑运算(logical)三大类。(需包含头文件#include <functional>)
(1) 六个算术运算:plus<type>, minus<type>, negate<type>, multiplies<type>, divides<type>, modules<type>.
(2) 六个关系运算:less<type>, less_equal<type>, greater<type>, greater_equal<type>, equal_to<type>, not_equal_to<type>.
(3) 三个逻辑运算:logical_and<type>, logical_or<type>, logical_not<type>.
7、Function Object Adapter.
function object adapter会对function object进行修改操作。所谓binder adapter(绑定适配器)会将function object的参数绑定至某特定值,使binary (二元) function object 转化为 unary (一元) function object。
标准库提供了两个binder adapter : bind1st 会将指定值绑定至第一操作数,bind2nd则将指定值绑定至第二操作数。
template <typename InputIterator, typename OutputIterator, typename ElemType, typename Comp>
OutputIterator filter( InputIterator first, InputIterator last, OutputIterator at, const ElemType &val, Comp pred )
{
while ( ( first = find_if( first, last, bind2nd( pred, val ) ) ) != last )
{
cout << "found value: " << *first << endl;
//执行assign操作,然后令两个iterator前进
*at = *first++;
}
return at;
}
8、<map> <multimap>
map<string, int> words;
words.first 对应 key 值,words.second 对应 value。
9、<set> <multiset>
默认情况下,set元素皆依据其所属类型默认的less-than运算符进行排列。与set相关的泛型算法:set_intersection(), set_union(), set_difference() 和 set_symmetric_difference().
标准库提供三个所谓的 insertion adapter :
back_inserter(), inserter(), front_inserter(). 使用包含<iterator>
10、面向对象编程概念的两项最主要特质是:继承(inheritance)和多态(polymorphism)。前者使我们得以将一群相关的类组织起来,并让我们分享其间的共同数据和操作行为,后者让我们在这些类之上编程时,可以如同操控单一个体,而并非相互独立的类,并赋予我们更多弹性来加入或移除特定类。
11、当基类的虚函数返回某个基类形式(通常是pointer或reference)时,派生类中的同名函数便可以返回该基类所派生出来的类型。
12、template参数可以是常量表达式(constant expression)、函数地址等。
template<int len, int beg_pos = 1>
class num_sequence;
template< void (*pf)(int pos, vector<int> &seq) >
13、当需要将多笔不同类型的数据格式化为字符串时。
#include <sstream>
ostringstream 自动将传给它的数值对象转换为相应字符串。
ostringstream ex_msg;
static string msg;
ex_msg << "Internal error: current index"
<<_index << "exceeds maxinum bound: "
<<_max;
msg = ex_msg.str(); //输出string对象
msg.c_str(); //转化为字符串