string 字符串類型與 auto 類型推導std::string:C++ 風格的字符串處理char msg[32]; msg[0]='G'; msg[1]='o'; msg[2]='o'; msg[3]='d'; msg[4]='\0'; cout << msg;
'\0'cstring 繁瑣函數std::string:自動管理內存的字符序列#include <string>
using namespace std;
string s = "Good Morning!";
cout << s.length() << endl; // 13
cout << s.find("Mor") << endl; // 5
s += " World"; // 直接拼接
length/size, find/rfind, substr, append, replace...+, +=, ==, < 等運算符wstringwstring ws = L"陝A-82103"; // L 前綴表寬字符串字面量
wcout.imbue(locale("chs")); // 設置中文區域
wcout << ws << endl;
string 對應 char(窄字符,通常 ASCII/UTF-8)wstring 對應 wchar_t(寬字符,Windows 下 UTF-16,Linux 下 UTF-32)string 或 wstring;中文建議用 wstring 避免編碼亂碼wcout,需 imbue(locale) 設置正確區域auto:讓編譯器幫你推導類型auto x = 7; // int
auto y = 1.982; // double
auto p = new Foo(); // Foo*
auto f = [](int a){ return a*2; }; // lambda 閉包類型
auto x = expr;auto x{expr}; (C++11 推導為 initializer_list,C++17 修正為單值類型)auto x; // 錯誤:無初始值無法推導
template <typename T>
void printAll(const vector<T>& v) {
for (auto it = v.begin(); it != v.end(); ++it)
cout << *it << '\n';
// 對比 C++98:
// for (typename vector<T>::const_iterator it = v.begin(); ...)
}
template <typename T, typename U>
auto mul(const T& a, const U& b) -> decltype(a*b) {
return a * b; // 返回類型由 a*b 推導
}
配合尾置返回類型 -> decltype(...),解決「模板函數返回類型無法預知」的難題。
decltype:獲取表達式類型,而不求值int x = 3; decltype(x) y = 5; // int decltype((x)) z = y; // int& (加括號變左值表達式) decltype(x+0.0) w = 1.5; // double
auto:根據初始值推導變量類型,用於變量定義decltype:根據表達式推導類型,用於類型聲明、返回類型、typedeftemplate <typename T, typename U>
void foo(const T& a, const U& b) {
typedef decltype(a*b) ResultType; // 獲得乘法結果類型
ResultType* p = new ResultType(); // 用於定義指針、創建對象...
}
| 特性 | auto | decltype |
|---|---|---|
| 推導依據 | 初始值表達式的值 | 表達式本身的類型 |
| 是否求值 | 是(需初始化) | 否(僅編譯期分析) |
| 主要用途 | 變量定義簡化 | 類型聲明、模板元編程 |
| 引用保留 | 默認去除引用(auto& 保留) | 保留表達式的值類別(左值→引用) |
auto 定義變量,特別是迭代器、Lambda、模板代碼。decltype + typedef/using。auto + 尾置 decltype(C++14 起可直接 auto 返回類型推導)。