所有工具
免费

可搜索、可打印的现代 C++ 参考——智能指针、容器、算法、RAII、移动语义、模板和并发。免费。

Basics, auto & references

11
auto x = 42;
Type deduction (int here)
const auto& r = bigObject;
Cheap read-only reference
int& ref = x; ref = 5;
Reference: alias to a variable
constexpr int N = 10;
Compile-time constant
using Ids = std::vector<int>;
Type alias (modern typedef)
auto [key, value] = *map.begin();
Structured bindings (C++17)
if (auto it = m.find(k); it != m.end())
Init-statement inside if (C++17)
enum class Color { Red, Green };
Scoped enum (no implicit int)
nullptr
Typed null pointer (never NULL)
static_cast<int>(3.99)
Explicit checked-style cast
std::int64_t n = 0; // <cstdint>
Fixed-width integer types

Smart pointers

10
auto p = std::make_unique<Widget>(args);
Sole owner, freed on scope exit
auto s = std::make_shared<Widget>();
Ref-counted shared ownership
std::unique_ptr<Widget> q = std::move(p);
Transfer ownership (no copy)
std::weak_ptr<Widget> w = s;
Non-owning observer of shared
if (auto sp = w.lock()) sp->run();
Safely promote weak → shared
p.get()
Raw pointer view (no ownership)
p.reset();
Destroy the owned object early
s.use_count()
Current shared reference count
void observe(const Widget& w);
Pass & or * to non-owners
std::unique_ptr<T[]> a = std::make_unique<T[]>(n);
Owned dynamic array

Containers

12
std::vector<int> v{1, 2, 3};
Dynamic array (default choice)
v.push_back(4); v.emplace_back(args);
Append (emplace constructs)
v.reserve(1000);
Pre-allocate to avoid regrowth
std::map<std::string, int> m;
Sorted key→value tree
std::unordered_map<std::string, int> h;
Hash map (faster, unsorted)
m["hits"] += 1; m.at("hits");
[] inserts default; at() throws
if (m.contains(key)) ...
Membership test (C++20)
std::array<int, 3> a{1, 2, 3};
Fixed-size stack array
void f(std::span<const int> s);
Non-owning view of any array
std::set<int> s; std::unordered_set<int> u;
Unique-element containers
std::erase_if(v, [](int n) { return n < 0; });
Erase-remove in one call (C++20)
v.size(); v.empty(); v.clear();
Common capacity operations

Algorithms & ranges

12
std::ranges::sort(v);
Sort a whole container (C++20)
std::sort(v.begin(), v.end(), cmp);
Classic iterator-pair sort
auto it = std::ranges::find_if(v, pred);
First element matching pred
std::transform(v.begin(), v.end(), out, f);
Map each element into out
std::accumulate(v.begin(), v.end(), 0)
Sum / fold (<numeric>)
std::ranges::count_if(v, pred)
Count matching elements
v | std::views::filter(isEven)
Lazy filtered view (C++20)
| std::views::transform(square)
Chain lazy transformations
std::views::iota(0, 10)
Lazy range of ints 0..9
auto v2 = r | std::ranges::to<std::vector>();
Materialize a view (C++23)
std::ranges::max_element(v)
Iterator to the largest value
std::ranges::any_of(v, pred)
any_of / all_of / none_of

Strings & string_view

11
std::string s = "hi"; s += "!";
Owning, growable string
void f(std::string_view sv);
Non-owning read-only view
if (s.find("x") != std::string::npos)
Substring search
s.substr(1, 3)
Slice (pos, length)
s.starts_with("http"); s.ends_with(".h");
Prefix / suffix tests (C++20)
s.contains("needle")
Substring test (C++23)
std::to_string(42)
Number → string
int n = std::stoi("42");
String → int (stod, stol...)
std::format("{}: {}", key, count)
Type-safe formatting (C++20)
std::getline(std::cin, line);
Read a whole input line
R"(C:\path\no "escapes")"
Raw string literal

Classes & RAII

11
struct Point { int x = 0; int y = 0; };
struct: public by default
Widget() : size_{0}, name_{"w"} {}
Member initializer list
~Widget() { close(handle_); }
Destructor releases resources
ctor, dtor, copy ctor/=, move ctor/=
Rule of five (define all or none)
Widget(const Widget&) = delete;
Forbid copying
Widget(Widget&&) noexcept = default;
Opt into generated move
explicit Widget(int size);
Block implicit conversions
int size() const { return size_; }
const member: no mutation
virtual void draw(); / void draw() override;
Polymorphism + override check
virtual ~Base() = default;
Virtual dtor for base classes
[[nodiscard]] bool ok() const;
Warn when return is ignored

Move semantics

9
auto b = std::move(a);
Cast to rvalue: steal resources
Widget(Widget&& o) noexcept;
Move constructor signature
return result;
Return by value: NRVO or move
void set(std::string s) { s_ = std::move(s); }
Sink param: by value + move
v.push_back(std::move(str));
Move into a container
auto old = std::exchange(ptr_, nullptr);
Take value, reset the source
std::swap(a, b);
Exchange two values cheaply
// moved-from: valid but unspecified
Only assign/destroy after move
template <class T> void f(T&& x) { g(std::forward<T>(x)); }
Perfect forwarding

Templates & concepts

10
template <typename T> T maxOf(T a, T b);
Function template
template <std::integral T> T half(T n);
Constrain with a concept (C++20)
template <class T> concept Number = std::is_arithmetic_v<T>;
Define a custom concept
void print(const auto& x);
Abbreviated template (C++20)
if constexpr (std::is_integral_v<T>)
Compile-time branch
std::pair p{1, 2.5};
CTAD: deduce class template args
template <typename... Args> void log(Args&&... args);
Variadic template
(args + ...)
Fold expression over a pack
template <class T> requires Number<T> T sq(T x);
requires clause
template <> struct Hash<Key> { ... };
Explicit specialization

Lambdas & std::function

10
auto twice = [](int x) { return x * 2; };
Basic lambda
[=] captures copies; [&] captures refs
Default capture modes
[x, &total](int n) { total += x * n; }
Mixed explicit captures
[this] { return counter_; }
Capture the enclosing object
[p = std::move(ptr)] { p->run(); }
Init-capture (move into lambda)
[n = 0]() mutable { return ++n; }
mutable: modify captured copies
[](auto a, auto b) { return a < b; }
Generic lambda
[](int x) -> double { return x / 2.0; }
Explicit return type
std::function<int(int)> cb = twice;
Type-erased callable holder
std::ranges::sort(v, {}, &User::age);
Projection instead of a lambda

Error handling

11
std::optional<int> parse(std::string_view s);
Maybe-a-value return type
opt.value_or(0)
Unwrap with a fallback
if (opt) use(*opt);
Test then dereference
std::expected<Data, Error> load();
Value-or-error return (C++23)
res.and_then(step).transform(format)
Monadic chaining (C++23)
throw std::runtime_error("bad config");
Throw a standard exception
catch (const std::exception& e) { e.what(); }
Catch by const reference
void close() noexcept;
Promise not to throw
assert(ptr != nullptr);
Debug-only invariant check
static_assert(sizeof(int) == 4);
Compile-time assertion
std::variant<int, Err> v; std::visit(fn, v);
Closed sum type + visitor

Concurrency

10
std::jthread t(work);
Auto-joining thread (C++20)
std::thread t(work); t.join();
Classic thread (must join)
std::mutex m; std::lock_guard lock(m);
Scoped lock (RAII)
std::scoped_lock lock(m1, m2);
Lock several without deadlock
std::unique_lock lk(m); cv.wait(lk, ready);
Condition variable wait
std::atomic<int> hits{0}; ++hits;
Lock-free counter
auto f = std::async(std::launch::async, fetch);
Run async, get a future
auto result = f.get();
Block until the result is ready
std::this_thread::sleep_for(100ms);
Sleep (std::chrono_literals)
thread_local int cache = 0;
One instance per thread

Compilation & CMake

11
g++ -std=c++23 -Wall -Wextra -O2 main.cpp -o app
Typical release compile
clang++ -std=c++20 main.cpp -o app
Same flags work with clang
-g -O0
Debug build (symbols, no opt)
-fsanitize=address,undefined
Catch memory/UB bugs at runtime
-Iinclude -Llib -lfoo
Header path, lib path, link lib
-DNDEBUG
Strip assert() in release
cmake_minimum_required(VERSION 3.20)
CMakeLists.txt first line
add_executable(app main.cpp)
Declare the binary target
target_compile_features(app PRIVATE cxx_std_23)
Require a C++ standard
cmake -B build && cmake --build build
Configure then build
cmake --build build -j 8
Parallel build

没有条目匹配“:q”。


关于 C++ 速查表

这份 C++ 速查表将现代 C++ 汇集到一个可搜索的参考页面上:基础知识、auto 和引用、智能指针、容器、算法和 Ranges、字符串和 string_view、类和 RAII、移动语义、模板和 Concepts、Lambda 和 std::function、错误处理、并发,以及 CMake 编译。

它聚焦于人们实际编写的现代 C++——unique_ptr 和 shared_ptr 取代裸 new 和 delete、基于范围的算法、结构化绑定、模板上的 Concepts、std::thread 和 std::mutex——同时仍详细阐述了五法则和 RAII 等基础概念。

与本系列的其他速查表一样,它免费且在客户端运行:使用搜索框实时过滤行,通过固定目录在章节间跳转,点击即可复制任何代码片段,还可以打印页面作为桌边参考。

如何使用 C++ 速查表

  1. 打开速查表,浏览各章节,从“基础知识、auto 和引用”到“编译和 CMake”。
  2. 搜索关键词如 unique_ptr、ranges 或 concept 以实时过滤。
  3. 需要较难语法的详细说明时跳转到“移动语义”或“模板和 Concepts”。
  4. 点击代码片段或其复制图标,将 C++ 代码复制到剪贴板。
  5. 使用打印功能获取完整 C++ 参考的纸质版。

常见问题

十二个章节:基础知识、auto 和引用、智能指针、容器、算法和 Ranges、字符串和 string_view、类和 RAII、移动语义、模板和 Concepts、Lambda 和 std::function、错误处理、并发,以及 CMake 编译。

现代风格。它以智能指针、RAII、移动语义、结构化绑定、Ranges 和 Concepts 为先导,而非手动内存管理。

有的。容器和算法章节列出了 vector、map、unordered_map、set、deque 以及常用算法——sort、find、transform、accumulate——并提供了基于范围的写法。

可以。点击任意行的代码或其复制图标,即可立即复制。

是的,完全免费,在浏览器中运行,无需登录。


热门搜索
c++ 速查表 现代 c++ 参考手册 c++ 智能指针 stl 容器速查表 c++ 算法列表 c++ 移动语义 c++ 模板和概念
需要帮助?
使用此工具时遇到问题?请告诉我们的团队。
报告问题

将此免费工具添加到你自己的网站 — 复制并粘贴下面的代码。