前言html
這是我閱讀《The C++ standard library, 2nd Edition》所作讀書筆記的第一篇。這個系列基本上會以一章一篇的節奏來寫,少數以C++03爲主的章節會和其它章節合併,一些內容較多的章節也會抽出幾個獨立的章節。這些博文不分析具體的應用情景,僅僅用來記錄C++11新增的知識點。關於C++11知識點的詳細解析,請參考C++11 FAQ;關於C++03以及STL的較詳盡解析,請參考相關著做或者網絡資料;推薦《C++ Primer,4th edition》和《The C++ Standard Library》。c++
(原書第三章:New Language Features)編程
新語言特性數組
vector<list<int>> vli; // OK
vector<VeryVeryLongLongType> foo; ... auto iter = foo.begin(); // iter是一個迭代器。 auto bar = [&](int)->bool{return ...}; // bar是一個lambda函數。能夠這樣調用:bar(3)。
int values[] {1 , 1, 2, 3, 5, 8, 13}; // 初始化列表不能進行變量的不精確轉換int a {1.0};是錯誤的。 std::vector<std::string> vs {"c++", "is", "upgrading"}; std::initializer_list<int> il = {1, 2, 3, 4}; // 用來接受{1, 2, 3, 4}的新類型,initializer_list。 class Foo { ... Foo(std::initializer_list<int>& lst); ...}; ... Foo foo {1, 2, 3, 4}; // 注意:構造函數的參數列表能夠隱式轉換爲initializer_list
for (int i : {1, ,1, 2, 3, 5, 8, 13, 21}) // 初始化列表格式 cout << i << endl; vector<int> vect; ... for (auto& item : vect) // 要改變值,要用 auto&, 引用 item *= 3;
X foo() { X x; ... return x; }
const char* pFile = R"(C:\Windows\Somepath.file)";// 等價於 "C:\\Windows\\Somepath.file"; const char* pName = R"nc(Alcohol"(wine)")nc"; // 若是字符串中出現"(或者)",能夠加入分隔符,好比nc。 const char* pUtf8 = u8"utf8字符串"; // u8表示utf8字符串; const char16_t* pChar16t = u"雙字節字符串"; // u表示雙字節字符串; const char32_t* pChar32t = U"四字節字符串"; // U表示四字節字符串; const wchar_t* pwchart = L"寬字符串"; // L表示寬字符串;
注意,R格式的字面值,能夠用u8,u,U,L修飾。網絡
template <typename T, typename ... Types> void print(const T& arg0, const Types&... args) { std::cout << arg0 <<std::endl; // 打印第一個值。 print(args...); // 打印剩餘的值。遞歸嗎? }
std::tuple<>大量使用這個特性。閉包
template<typename T> using Vec = std::vector<T, MyAlloc<T>>; // Vec是一個別名模板,它是std::vector<T, MyAlloc<T>>的別名; // 模板別名的聲明格式: template<typename T> using alias = ...; Vec<int> vec;
template<typename T1, typename T2> auto add(T1 x, T2 y)->decltype(x + y) {...} // 與lambda的聲明相似。add的返回類型,是x + y的類型。可是在C++11以前是不可行的。
enum class Salution : char{mr, ms, co, none};