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(); //轉化爲字符串