Справочник за съвременен 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, лямбда изрази и std::function, обработка на грешки, паралелизъм и компилиране с CMake.

It is aimed at the C++ people actually write today: unique_ptr and shared_ptr instead of raw new and delete, range-based algorithms, structured bindings, concepts on templates, std::thread and std::mutex; while still spelling out the fundamentals like the rule of five and RAII.

Както всяка бърза справка в тази група, тя е безплатна и от страна на клиента: филтрирайте редовете на живо с полето за търсене, скачайте между разделите от фиксираното съдържание, копирайте всеки откъс с едно щракване и отпечатайте страницата като справочник за бюрото.

Как да използвате Бърза справка за C++

  1. Отворете справката и прегледайте разделите, от Основи, auto и референции до Компилиране и CMake.
  2. Търсете ключова дума като unique_ptr, ranges или concept, за да филтрирате справката на живо.
  3. Отидете на Семантика на местене или Шаблони и concepts, когато ви трябва по-трудният синтаксис, обяснен подробно.
  4. Щракнете върху откъс или неговата иконка за копиране, за да копирате C++ кода в клипборда си.
  5. Използвайте Печат за хартиено копие на пълния справочник за C++.

Често задавани въпроси

Дванадесет раздела: основи с auto и референции, умни показалци, контейнери, алгоритми и ranges, низове и string_view, класове и RAII, семантика на местене, шаблони и concepts, лямбда изрази и std::function, обработка на грешки, паралелизъм и компилиране с CMake.

Съвременен. Започва с умни показалци, RAII, семантика на местене, структурирано свързване, ranges и concepts, вместо ръчно управление на паметта.

Да. Разделите за контейнери и алгоритми изброяват vector, map, unordered_map, set, deque и обичайните алгоритми (sort, find, transform, accumulate) с техните форми, базирани на ranges.

Да. Щракнете върху кода на който и да е ред или неговата иконка за копиране и той се копира веднага.

Да, напълно безплатен е и работи в браузъра ви без вход в акаунт.

Сподели

Популярни търсения
бърза справка за c++ справочник за съвременен c++ умни показалци в c++ бърза справка за stl контейнери списък с алгоритми в c++ семантика на местене в c++ шаблони и concepts в c++
Нуждаете се от помощ?
Открихте проблем с този инструмент? Кажете ни.
Докладване на проблем

Добавете този безплатен инструмент към собствения си уебсайт: копирайте и поставете кода по-долу.