2.1 数组
原始C风格数组
#include <iostream>
int main() {
// 声明与初始化
int arr1[5]; // 未初始化,值不确定
int arr2[5] = {1, 2, 3, 4, 5}; // 全部初始化
int arr3[5] = {1, 2}; // 部分初始化,其余为0
int arr4[] = {1, 2, 3, 4, 5}; // 自动推导大小
// 访问元素
arr2[0] = 100;
std::cout << "arr2[0] = " << arr2[0] << std::endl;
// 遍历
for (int i = 0; i < 5; ++i) {
std::cout << arr4[i] << " ";
}
std::cout << std::endl;
// 数组名退化为指针
int* ptr = arr4;
std::cout << "*ptr = " << *ptr << std::endl;
std::cout << "*(ptr+1) = " << *(ptr + 1) << std::endl;
// 数组大小
std::cout << "sizeof(arr4) = " << sizeof(arr4) << std::endl; // 5*4=20
std::cout << "元素个数 = " << sizeof(arr4) / sizeof(arr4[0]) << std::endl;
return 0;
}
std::array(推荐)
#include <iostream>
#include <array>
#include <algorithm>
int main() {
// 声明
std::array<int, 5> arr = {1, 2, 3, 4, 5};
// 常用操作
std::cout << "size: " << arr.size() << std::endl;
std::cout << "front: " << arr.front() << std::endl;
std::cout << "back: " << arr.back() << std::endl;
std::cout << "arr[2]: " << arr[2] << std::endl;
// 使用at()带边界检查
try {
std::cout << arr.at(2) << std::endl;
// std::cout << arr.at(10) << std::endl; // 抛出std::out_of_range
} catch (const std::out_of_range& e) {
std::cout << "Out of range: " << e.what() << std::endl;
}
// 遍历(基于范围的for循环)
for (const auto& elem : arr) {
std::cout << elem << " ";
}
std::cout << std::endl;
// 填充
arr.fill(42);
// 可以直接传递给需要指针的函数
void process(int* data, size_t size);
process(arr.data(), arr.size());
return 0;
}
void process(int* data, size_t size) {
for (size_t i = 0; i < size; ++i) {
std::cout << data[i] << " ";
}
std::cout << std::endl;
}
多维数组
#include <iostream>
#include <array>
int main() {
// C风格二维数组
int matrix1[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
// 访问
std::cout << "matrix1[1][2] = " << matrix1[1][2] << std::endl; // 7
// 使用std::array
std::array<std::array<int, 4>, 3> matrix2 = {{
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
}};
// 遍历
for (const auto& row : matrix2) {
for (const auto& elem : row) {
std::cout << elem << "\t";
}
std::cout << std::endl;
}
return 0;
}
2.2 指针
指针基础
#include <iostream>
int main() {
int value = 42;
int* ptr = &value; // ptr存储value的地址
std::cout << "value: " << value << std::endl;
std::cout << "&value: " << &value << std::endl;
std::cout << "ptr: " << ptr << std::endl;
std::cout << "*ptr: " << *ptr << std::endl; // 解引用
// 通过指针修改值
*ptr = 100;
std::cout << "new value: " << value << std::endl; // 100
// 空指针
int* null_ptr = nullptr; // C++11推荐
int* null_ptr2 = NULL; // 旧式(不推荐)
int* null_ptr3 = 0; // 旧式(不推荐)
// 检查空指针
if (ptr != nullptr) {
std::cout << "ptr is not null" << std::endl;
}
return 0;
}
const与指针
#include <iostream>
int main() {
int x = 10, y = 20;
// 指向const的指针:不能通过指针修改值
const int* p1 = &x;
// *p1 = 30; // 错误!
p1 = &y; // 可以改变指针指向
// const指针:指针本身不能改
int* const p2 = &x;
*p2 = 30; // 可以通过指针修改值
// p2 = &y; // 错误!
// const指针指向const:都不能改
const int* const p3 = &x;
// *p3 = 40; // 错误!
// p3 = &y; // 错误!
// 助记:从右向左读
// const int* => pointer to const int
// int* const => const pointer to int
// const int* const => const pointer to const int
return 0;
}
指针运算
#include <iostream>
int main() {
int arr[] = {10, 20, 30, 40, 50};
int* p = arr; // 指向数组首元素
std::cout << *p << std::endl; // 10
std::cout << *(p + 2) << std::endl; // 30(向后偏移2个元素)
std::cout << p[3] << std::endl; // 40(等价于*(p+3))
// 遍历数组
int* end = arr + 5;
for (int* it = arr; it != end; ++it) {
std::cout << *it << " ";
}
std::cout << std::endl;
// 指针相减
int* p1 = &arr[1];
int* p2 = &arr[4];
std::ptrdiff_t diff = p2 - p1;
std::cout << "elements between: " << diff << std::endl; // 3
return 0;
}
函数指针
#include <iostream>
#include <functional>
int add(int a, int b) { return a + b; }
int multiply(int a, int b) { return a * b; }
// 接受函数指针作为参数
int compute(int x, int y, int (*operation)(int, int)) {
return operation(x, y);
}
// C++11起推荐使用std::function
int compute_v2(int x, int y, std::function<int(int, int)> op) {
return op(x, y);
}
int main() {
// 函数指针声明
int (*func_ptr)(int, int) = &add;
// 或简写:int (*func_ptr)(int, int) = add;
std::cout << "add: " << func_ptr(3, 5) << std::endl;
func_ptr = multiply;
std::cout << "multiply: " << func_ptr(3, 5) << std::endl;
// 作为参数传递
std::cout << "compute(add): " << compute(10, 5, add) << std::endl;
std::cout << "compute(multiply): " << compute(10, 5, multiply) << std::endl;
// 使用std::function(可以存储lambda)
std::function<int(int, int)> op = [](int a, int b) { return a - b; };
std::cout << "lambda: " << compute_v2(10, 5, op) << std::endl;
return 0;
}
2.3 引用
左值引用
#include <iostream>
#include <string>
int main() {
int x = 10;
int& ref = x; // ref是x的别名
ref = 20;
std::cout << "x = " << x << std::endl; // 20
// 引用必须初始化
// int& ref2; // 错误!
// 引用一旦绑定,不能改变
int y = 30;
ref = y; // 这不是改变ref的绑定,而是给x赋值
std::cout << "x = " << x << std::endl; // 30
// 常引用
const int& cref = x;
// cref = 40; // 错误!不能通过常引用修改
// 常引用可以绑定到临时对象
const int& temp_ref = 42; // OK,生命周期延长
// int& temp_ref2 = 42; // 错误!不能绑定到临时对象
// 引用作为函数参数(避免拷贝)
void modify(int& n) { n *= 2; }
modify(x);
std::cout << "x after modify: " << x << std::endl;
return 0;
}
右值引用(C++11)
#include <iostream>
#include <string>
#include <utility>
void process(const std::string& s) {
std::cout << "lvalue: " << s << std::endl;
}
void process(std::string&& s) {
std::cout << "rvalue: " << s << std::endl;
// 可以"窃取"资源
}
int main() {
std::string str = "hello";
process(str); // 调用左值版本
process(std::string("world")); // 调用右值版本
process(str + " cpp"); // 调用右值版本
process(std::move(str)); // 调用右值版本(str被移动后不应再使用)
// std::move将左值转换为右值引用
std::string s1 = "data";
std::string s2 = std::move(s1); // s1的内容被移走
std::cout << "s1 after move: '" << s1 << "'" << std::endl; // 空或未指定
std::cout << "s2: '" << s2 << "'" << std::endl; // "data"
return 0;
}
引用的应用场景
#include <iostream>
#include <vector>
#include <string>
// 1. 按引用传递(避免拷贝)
void to_upper(std::string& s) {
for (auto& c : s) {
if (c >= 'a' && c <= 'z') c -= 32;
}
}
// 2. 按常引用传递(只读,避免拷贝)
double average(const std::vector<int>& vec) {
if (vec.empty()) return 0.0;
double sum = 0;
for (int v : vec) sum += v;
return sum / vec.size();
}
// 3. 范围for中的引用(修改元素)
void double_elements(std::vector<int>& vec) {
for (auto& elem : vec) {
elem *= 2;
}
}
int main() {
std::string name = "hello";
to_upper(name);
std::cout << name << std::endl; // "HELLO"
std::vector<int> nums = {1, 2, 3, 4, 5};
std::cout << "average: " << average(nums) << std::endl;
double_elements(nums);
for (auto n : nums) std::cout << n << " ";
std::cout << std::endl;
return 0;
}
2.4 控制流程
条件语句(if/else if/else)
#include <iostream>
int main() {
int score = 85;
if (score >= 90) {
std::cout << "Excellent" << std::endl;
} else if (score >= 80) {
std::cout << "Good" << std::endl;
} else if (score >= 60) {
std::cout << "Pass" << std::endl;
} else {
std::cout << "Fail" << std::endl;
}
// C++17: if语句带初始化器
if (auto it = std::map<int, std::string>{{1, "one"}}.find(1);
it != std::map<int, std::string>::end()) {
std::cout << "Found: " << it->second << std::endl;
} else {
std::cout << "Not found" << std::endl;
}
return 0;
}
条件语句(switch)
#include <iostream>
int main() {
int day = 3;
switch (day) {
case 1:
std::cout << "Monday" << std::endl;
break;
case 2:
std::cout << "Tuesday" << std::endl;
break;
case 3:
std::cout << "Wednesday" << std::endl;
break;
case 4:
case 5:
std::cout << "Thursday or Friday" << std::endl;
break;
default:
std::cout << "Weekend" << std::endl;
break;
}
// C++17: switch带初始化器
switch (int code = get_status(); code) {
case 200: std::cout << "OK" << std::endl; break;
case 404: std::cout << "Not Found" << std::endl; break;
default: std::cout << "Other: " << code << std::endl; break;
}
// fallthrough属性(C++17,显式标注穿透)
switch (int n = 1; n) {
case 1:
std::cout << "Step 1" << std::endl;
[[fallthrough]];
case 2:
std::cout << "Step 2" << std::endl;
[[fallthrough]];
case 3:
std::cout << "Step 3" << std::endl;
break;
}
return 0;
}
循环语句(for)
#include <iostream>
#include <vector>
int main() {
// 传统for
for (int i = 0; i < 5; ++i) {
std::cout << i << " ";
}
std::cout << std::endl;
// 基于范围的for(C++11起)
std::vector<int> vec = {1, 2, 3, 4, 5};
for (int v : vec) {
std::cout << v << " ";
}
std::cout << std::endl;
// 使用auto和引用
for (const auto& v : vec) {
std::cout << v << " ";
}
std::cout << std::endl;
// 修改元素需要引用
for (auto& v : vec) {
v *= 2;
}
// C++20: 范围for带初始化器
// for (auto vec = get_data(); auto& v : vec) {
// std::cout << v << " ";
// }
// 遍历数组
int arr[] = {10, 20, 30, 40, 50};
for (int n : arr) {
std::cout << n << " ";
}
std::cout << std::endl;
return 0;
}
循环语句(while / do-while)
#include <iostream>
#include <vector>
int main() {
// while循环
int count = 0;
while (count < 5) {
std::cout << count << " ";
++count;
}
std::cout << std::endl;
// 常用模式:遍历操作
std::vector<int> vec = {1, 2, 3, 4, 5};
size_t i = 0;
while (i < vec.size()) {
std::cout << vec[i] << " ";
++i;
}
std::cout << std::endl;
// do-while循环(至少执行一次)
int n = 0;
do {
std::cout << "Executed at least once" << std::endl;
++n;
} while (n < 0); // 条件为假,但循环体已执行一次
return 0;
}
跳转语句
#include <iostream>
int main() {
// break:跳出当前循环
for (int i = 0; i < 10; ++i) {
if (i == 5) break;
std::cout << i << " ";
}
std::cout << std::endl; // 0 1 2 3 4
// continue:跳过当前迭代
for (int i = 0; i < 10; ++i) {
if (i % 2 == 0) continue; // 跳过偶数
std::cout << i << " "; // 只输出奇数
}
std::cout << std::endl; // 1 3 5 7 9
// break在嵌套循环中只跳出内层
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
if (j == 1) break; // 只跳出内层循环
std::cout << "(" << i << "," << j << ") ";
}
}
std::cout << std::endl;
return 0;
}
2.5 函数
函数定义与调用
#include <iostream>
#include <string>
// 函数声明(原型)
double calculate_area(double width, double height);
// 带默认参数的函数
std::string greet(const std::string& name = "World") {
return "Hello, " + name + "!";
}
// 内联函数
inline int max(int a, int b) {
return (a > b) ? a : b;
}
int main() {
std::cout << "Area: " << calculate_area(5.0, 3.0) << std::endl;
std::cout << greet() << std::endl; // 使用默认参数
std::cout << greet("Alice") << std::endl;
std::cout << "max(10, 20): " << max(10, 20) << std::endl;
return 0;
}
// 函数定义
double calculate_area(double width, double height) {
return width * height;
}
函数重载
#include <iostream>
#include <string>
// 同名函数,不同参数类型或数量
void print(int value) {
std::cout << "int: " << value << std::endl;
}
void print(double value) {
std::cout << "double: " << value << std::endl;
}
void print(const std::string& value) {
std::cout << "string: " << value << std::endl;
}
void print(int a, int b) {
std::cout << "two ints: " << a << ", " << b << std::endl;
}
// 注意:返回值类型不同不能作为重载条件
// int func(); 和 double func(); 是冲突的(除非调用时返回值被使用)
int main() {
print(42);
print(3.14);
print(std::string("hello"));
print(10, 20);
return 0;
}
默认参数
#include <iostream>
// 默认参数从右向左排列
void configure(int width, int height = 100, bool visible = true) {
std::cout << "w=" << width << ", h=" << height
<< ", visible=" << std::boolalpha << visible << std::endl;
}
// 注意:默认参数只能出现在声明或定义中的一处
// 通常放在声明中(头文件里)
int main() {
configure(800); // w=800, h=100, visible=true
configure(800, 600); // w=800, h=600, visible=true
configure(800, 600, false); // w=800, h=600, visible=false
return 0;
}
函数返回值
#include <iostream>
#include <string>
#include <optional>
#include <utility>
// 单返回值
int add(int a, int b) { return a + b; }
// 多返回值:使用std::pair
std::pair<int, int> divide(int a, int b) {
return {a / b, a % b}; // 商和余数
}
// 多返回值:使用std::tuple(C++11)
std::tuple<std::string, int, double> get_person() {
return {"Alice", 30, 65.5};
}
// 多返回值:使用结构化绑定(C++17)
auto get_stats() {
struct Stats { double min, max, avg; };
return Stats{1.0, 100.0, 50.5};
}
// 使用std::optional处理可能失败的返回值(C++17)
std::optional<int> safe_divide(int a, int b) {
if (b == 0) return std::nullopt;
return a / b;
}
int main() {
// pair接收
auto [quotient, remainder] = divide(10, 3);
std::cout << "10/3 = " << quotient << " remainder " << remainder << std::endl;
// tuple接收
auto [name, age, weight] = get_person();
std::cout << name << ", " << age << ", " << weight << "kg" << std::endl;
// 结构体结构化绑定
auto [min, max, avg] = get_stats();
std::cout << "min=" << min << " max=" << max << " avg=" << avg << std::endl;
// optional
auto result = safe_divide(10, 0);
if (result.has_value()) {
std::cout << "Result: " << result.value() << std::endl;
} else {
std::cout << "Division by zero" << std::endl;
}
// 使用value_or提供默认值
int safe = safe_divide(10, 0).value_or(-1);
std::cout << "safe result: " << safe << std::endl;
return 0;
}
Lambda表达式
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
int main() {
// 基本lambda语法:[捕获列表](参数列表) -> 返回类型 { 函数体 }
auto hello = []() { std::cout << "Hello, Lambda!" << std::endl; };
hello();
// 带参数的lambda
auto add = [](int a, int b) -> int { return a + b; };
std::cout << "1 + 2 = " << add(1, 2) << std::endl;
// 省略返回类型(自动推导)
auto multiply = [](int a, int b) { return a * b; };
// 值捕获
int x = 10;
auto by_value = [x]() { return x * 2; }; // x是只读副本
// [=] 以值捕获全部外部变量
// 引用捕获
auto by_ref = [&x]() { x *= 2; }; // x被引用,可以修改
// [&] 以引用捕获全部外部变量
// 可变lambda(允许修改值捕获的副本)
auto mutable_lambda = [x]() mutable { x *= 2; return x; };
// 混合捕获
int a = 1, b = 2, c = 3;
auto mixed = [a, &b, &c]() {
// a是值捕获(只读)
// b和c是引用捕获
b = a + c;
};
// 泛型lambda(C++14)
auto generic = [](auto a, auto b) { return a + b; };
std::cout << generic(1, 2) << std::endl;
std::cout << generic(std::string("hello "), std::string("world")) << std::endl;
// lambda在STL算法中的应用
std::vector<int> vec = {5, 2, 8, 1, 9, 3};
std::sort(vec.begin(), vec.end(),
[](int a, int b) { return a > b; }); // 降序排列
// 查找第一个满足条件的元素
auto it = std::find_if(vec.begin(), vec.end(),
[](int n) { return n > 5; });
if (it != vec.end()) {
std::cout << "First > 5: " << *it << std::endl;
}
// 立即执行的lambda(IIFE)
int result = [](int n) {
int sum = 0;
for (int i = 1; i <= n; ++i) sum += i;
return sum;
}(100);
std::cout << "Sum 1..100 = " << result << std::endl;
// 将lambda赋值给std::function
std::function<int(int, int)> operation = add;
std::cout << "function: " << operation(3, 4) << std::endl;
return 0;
}
2.6 字符串
std::string基本操作
#include <iostream>
#include <string>
int main() {
// 构造
std::string s1; // 空字符串
std::string s2 = "Hello"; // 从C字符串
std::string s3("World"); // 直接构造
std::string s4(5, 'A'); // "AAAAA"
std::string s5(s2); // 拷贝构造
// 基本属性
std::cout << "s2: " << s2 << std::endl;
std::cout << "length: " << s2.length() << std::endl;
std::cout << "size: " << s2.size() << std::endl;
std::cout << "empty: " << s2.empty() << std::endl;
// 访问字符
char first = s2[0]; // 无边界检查
char first_safe = s2.at(0); // 有边界检查
char& back = s2.back(); // 最后一个字符
// 拼接
std::string full = s2 + " " + s3; // 运算符+
full += "!"; // 运算符+=
full.append(" C++"); // append方法
// 子串
std::string sub = full.substr(0, 5); // 从位置0取5个字符
std::string tail = full.substr(6); // 从位置6到末尾
// 查找
size_t pos = full.find("World");
if (pos != std::string::npos) {
std::cout << "'World' found at position: " << pos << std::endl;
}
// 是否包含(C++23有contains,之前用find判断)
bool contains = full.find("Hello") != std::string::npos;
// 替换
full.replace(6, 5, "C++");
// 插入
full.insert(0, "Say: ");
// 删除
full.erase(0, 4);
// 比较
if (s2 == s3) { /* equal */ }
int cmp = s2.compare(s3); // 0:相等, <0:小于, >0:大于
// 大小写转换(C++没有内置,需要算法)
std::string upper = full;
for (auto& c : upper) c = std::toupper(c);
std::cout << "Final: " << full << std::endl;
return 0;
}
字符串分割与连接
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <numeric>
// 分割字符串
std::vector<std::string> split(const std::string& str, char delimiter) {
std::vector<std::string> tokens;
std::istringstream ss(str);
std::string token;
while (std::getline(ss, token, delimiter)) {
tokens.push_back(token);
}
return tokens;
}
// 连接字符串
std::string join(const std::vector<std::string>& tokens, const std::string& delimiter) {
if (tokens.empty()) return "";
return std::accumulate(
std::next(tokens.begin()), tokens.end(), tokens[0],
[&delimiter](const std::string& a, const std::string& b) {
return a + delimiter + b;
});
}
int main() {
std::string data = "apple,banana,cherry,grape";
// 分割
auto fruits = split(data, ',');
for (const auto& f : fruits) {
std::cout << f << std::endl;
}
// 连接
std::string rejoined = join(fruits, " | ");
std::cout << "Rejoined: " << rejoined << std::endl;
return 0;
}
std::string_view(C++17)
std::string_view 是一个轻量级的非拥有型字符串视图,不分配内存,适合作为函数参数。
#include <iostream>
#include <string>
#include <string_view>
// 使用string_view作为参数,避免不必要的拷贝
bool starts_with(std::string_view sv, std::string_view prefix) {
return sv.substr(0, prefix.size()) == prefix;
}
// 使用string_view处理多种字符串类型
void process(std::string_view sv) {
std::cout << "Length: " << sv.length() << std::endl;
std::cout << "Content: " << sv << std::endl;
// 子视图(O(1),不分配内存)
auto sub = sv.substr(0, 5);
std::cout << "First 5: " << sub << std::endl;
// 移除前缀
sv.remove_prefix(1);
// 移除后缀
sv.remove_suffix(1);
}
int main() {
// 可以从多种类型构造
process("C-string literal");
process(std::string("std::string"));
process(std::string_view("another view"));
std::cout << std::boolalpha;
std::cout << starts_with("hello world", "hello") << std::endl; // true
std::cout << starts_with("hello world", "world") << std::endl; // false
// 注意:string_view不拥有数据,要确保底层数据在view使用期间有效
// std::string_view bad_view = std::string("temp"); // 危险!临时对象被销毁
std::string s = "safe";
std::string_view safe_view = s; // OK,s的生命周期覆盖view
return 0;
}
2.7 枚举
传统枚举
#include <iostream>
// 传统枚举(非作用域枚举)
enum Color {
RED, // 0
GREEN, // 1
BLUE // 2
};
enum Size {
SMALL = 1,
MEDIUM = 5,
LARGE = 10
};
int main() {
Color c = RED; // 可以直接使用
int val = RED; // 隐式转换为int
// 问题:命名冲突
// enum TrafficLight { RED, YELLOW, GREEN }; // 错误!RED和GREEN重复
std::cout << "RED = " << RED << std::endl;
return 0;
}
enum class(C++11,推荐)
#include <iostream>
// 作用域枚举(强类型枚举)
enum class Color {
RED,
GREEN,
BLUE
};
enum class TrafficLight {
RED,
YELLOW,
GREEN
};
// 指定底层类型
enum class Permission : uint8_t {
NONE = 0,
READ = 1 << 0, // 1
WRITE = 1 << 1, // 2
EXEC = 1 << 2 // 4
};
// 重载位运算运算符
Permission operator|(Permission a, Permission b) {
return static_cast<Permission>(
static_cast<uint8_t>(a) | static_cast<uint8_t>(b));
}
Permission operator&(Permission a, Permission b) {
return static_cast<Permission>(
static_cast<uint8_t>(a) & static_cast<uint8_t>(b));
}
int main() {
Color c = Color::RED; // 必须使用作用域限定符
TrafficLight t = TrafficLight::RED; // 不会冲突
// int i = Color::RED; // 错误!不能隐式转换
int i = static_cast<int>(Color::RED); // 正确,显式转换
std::cout << "Color::RED = " << i << std::endl;
// 位标志用法
Permission p = Permission::READ | Permission::WRITE;
bool can_read = (p & Permission::READ) == Permission::READ;
std::cout << "can_read: " << can_read << std::endl;
return 0;
}
2.8 结构化绑定(C++17)
#include <iostream>
#include <map>
#include <tuple>
#include <array>
struct Point {
double x, y;
};
int main() {
// 绑定到数组
int arr[] = {1, 2, 3};
auto [a, b, c] = arr;
std::cout << a << ", " << b << ", " << c << std::endl;
// 绑定到结构体
Point p{10.5, 20.3};
auto [x, y] = p;
std::cout << "x=" << x << ", y=" << y << std::endl;
// 绑定到pair
std::pair<int, std::string> pair{1, "one"};
auto [num, str] = pair;
// 绑定到tuple
auto tuple = std::make_tuple(42, 3.14, "hello");
auto [i, d, s] = tuple;
std::cout << i << ", " << d << ", " << s << std::endl;
// 绑定到map迭代(最经典用法)
std::map<int, std::string> m{{1, "one"}, {2, "two"}, {3, "three"}};
for (const auto& [key, value] : m) {
std::cout << key << " => " << value << std::endl;
}
// 使用引用修改
Point& ref_p = p;
auto& [rx, ry] = ref_p;
rx = 100;
std::cout << "p.x = " << p.x << std::endl; // 100
return 0;
}
2.9 字面量
#include <iostream>
#include <string>
#include <chrono>
int main() {
// 整数字面量后缀
int a = 42; // int
unsigned u = 42u; // unsigned
long l = 42L; // long
long long ll = 42LL; // long long
unsigned long long ull = 42ULL;
// 进制前缀(C++14二进制字面量)
int dec = 255; // 十进制
int hex = 0xFF; // 十六进制
int oct = 0377; // 八进制
int bin = 0b11111111; // 二进制(C++14)
// 数字分隔符(C++14)
long large = 1'000'000;
int mask = 0b1010'1100'1111'0000;
double precise = 3.141'592'653;
// 浮点字面量
float f = 3.14f;
double d = 3.14;
long double ld = 3.14L;
// 字符串字面量
const char* cs = "C string";
std::string cpps = "C++ string";
const wchar_t* ws = L"wide string";
const char* raw = R"(raw "string" with \n no escape)"; // 原始字符串(C++11)
// 自定义分隔符的原始字符串
const char* raw_delim = R"DELIM(
This is a raw string with "quotes" and \backslashes.
No escaping needed!
)DELIM";
// 用户定义字面量(C++11)
using namespace std::string_literals;
auto str = "hello"s; // std::string字面量
using namespace std::string_view_literals;
auto sv = "hello"sv; // std::string_view字面量
using namespace std::chrono_literals;
auto sec = 5s; // std::chrono::seconds
auto ms = 100ms; // std::chrono::milliseconds
auto us = 50us; // std::chrono::microseconds
return 0;
}
2.10 using与类型别名
#include <iostream>
#include <vector>
#include <string>
#include <map>
// 旧式typedef
typedef unsigned long ulong;
typedef std::vector<std::string> StringVec;
typedef int (*FuncPtr)(int, int);
// C++11 using别名(推荐)
using ulong_t = unsigned long;
using StringVec_t = std::vector<std::string>;
using FuncPtr_t = int (*)(int, int);
// using别名在模板中的优势
template<typename T>
using Vec = std::vector<T>;
template<typename T>
using StringMap = std::map<std::string, T>;
int main() {
Vec<int> int_vec = {1, 2, 3}; // 等价于std::vector<int>
StringMap<double> scores; // 等价于std::map<std::string, double>
scores["Alice"] = 95.5;
scores["Bob"] = 88.0;
for (const auto& [name, score] : scores) {
std::cout << name << ": " << score << std::endl;
}
return 0;
}
2.11 本章小结
本章涵盖了C++核心语言特性:
- 数组(原始数组和std::array)
- 指针及相关运算
- 引用(左值引用和右值引用)
- 控制流程语句
- 函数定义、重载、默认参数和返回值
- Lambda表达式
- 字符串处理
- 枚举类型
- C++17结构化绑定
- 字面量表示
- 类型别名
这些是C++编程中日常使用最频繁的基础设施。