vector<list<int>>; //Error vector<list<int> >; //OK
vector<list<int>>; //OK
void f(int); void f(void*); f(0); //call f(int) f(NULL); //有歧義
f(nullptr);//call f(void*)
nullptr是關鍵詞,其類型是std::nullptr_tc++
auto i = 42; //int double f(); auto d = f(); //double auto n; //Error static auto vat = 0.19; vector<string> v; auto pos = v.begin(); auto f = [](int x)-> bool{return x+1;}
基本形式:express
for( decl : coll ){ statement }
等價於:函數
for( auto _pos = coll.begin(), _end = coll.end(); _pos != NULL; ++_pos){ decl = * _pos; statement }
或者(其中begin()和end()是全局函數):編碼
for( auto _pos = begin(coll), _end = end(coll); _pos != NULL; ++_pos){ decl = * _pos; statement }
for( int i : {2, 3, 4, 5,8} ){ std::cout<< i << std::endl; }
std::vector<double> vec; ... for( auto & elem : vec ){ elem *= 3; }
template < typename T> void printElements( const T& coll ){ for( const auto& elem : coll ){ std::cout<< elem << std::endl; } }
template < typename T> void printElements( const T& coll ){ for( const auto& elem : coll ){ std::cout<< elem << std::endl; } }
Get() const{ return m_data; } private: int m_data; }; ostream& operator<<(ostream& os, const X& x) { os << x.Get(); return os; } int main(){ vector<X> v = {1, 3, 5, 7, 9}; cout << "\nElements:\n"; for (auto x : v) { cout << x << ' '; } return 0; }
輸出:c++11
X copy ctor. X copy ctor. X copy ctor. X copy ctor. X copy ctor. Elements: X copy ctor. 1 X copy ctor. 3 X copy ctor. 5 X copy ctor. 7 X copy ctor. 9
爲了防止調用拷貝構造函數,提升下率,加上引用。code
for (auto &x : v) { cout << x << ' '; }
執行輸出:ci
X copy ctor. X copy ctor. X copy ctor. X copy ctor. X copy ctor. Elements: 1 3 5 7 9
發現已經不調用拷貝構造函數了。字符串
class C { public : explicit C( const std::string & s); //顯示轉換 ... }; int main(){ std::vector<std::string> vs; for( const C& elem : vs ){ std::cout << elem << std::endl; } }
報錯。去掉「explicit」後,可正常運行。string
invalid initialization of reference of type ‘const C&’ from expression of type ‘std::__cxx11::basic_string<char>’
在字符串前面加上關鍵字R,表示這是一個原始字符串。
下面這兩個是等效的。it
"\\\\n" R"\\n"
下面這兩個也是等效的。
R"nc(a\ b\nc()" )nc"; "nc(a\\\n b\\nc()\"\n )nc";
使用編碼前綴制定字符串編碼。以下
L"hello" // 定義wchar_t編碼的字符串
前綴有如下幾種:
- u8表示UTF-8編碼。
- u表示char16_t
- U表示char32_t
- L表示寬字符集,類型wchar_t
c++11中的枚舉類型以下所示:
enum class Salutation : char { mr, ms, co, none };