C++23新特性
C++23新特性详解:std::print、std::flat_map等。
1. std::print
#include <print>
std::print("Hello, {}!\n", "World");
std::println("Value: {}", 42);
std::print(stderr, "Error: {}\n", message);
2. std::flat_map / std::flat_set
#include <flat_map>
std::flat_map<std::string, int> scores;
scores["Alice"] = 95;
scores["Bob"] = 87;
// 基于排序连续存储,缓存友好
// 适合小数据量、读多写少场景
3. std::expected
#include <expected>
std::expected<int, std::string> divide(int a, int b) {
if (b == 0) return std::unexpected("division by zero");
return a / b;
}
auto result = divide(10, 2);
if (result) {
std::print("{}\n", result.value()); // 5
} else {
std::print("{}\n", result.error());
}
4. std::generator
#include <generator>
std::generator<int> fibonacci() {
int a = 0, b = 1;
while (true) {
co_yield a;
auto tmp = a;
a = b;
b = tmp + b;
}
}
5. 其他特性
if consteval:编译期判断std::is_implicit_lifetimestd::unreachable()std::string::contains()- 多维下标运算符
operator[]