Lembar Contekan C++
Referensi C++ modern yang bisa dicari dan dicetak: smart pointers, containers, algorithms, RAII, move semantics, templates, dan concurrency. Gratis.
Basics, auto & references
11auto x = 42;
const auto& r = bigObject;
int& ref = x; ref = 5;
constexpr int N = 10;
using Ids = std::vector<int>;
auto [key, value] = *map.begin();
if (auto it = m.find(k); it != m.end())
enum class Color { Red, Green };
nullptr
static_cast<int>(3.99)
std::int64_t n = 0; // <cstdint>
Smart pointers
10auto p = std::make_unique<Widget>(args);
auto s = std::make_shared<Widget>();
std::unique_ptr<Widget> q = std::move(p);
std::weak_ptr<Widget> w = s;
if (auto sp = w.lock()) sp->run();
p.get()
p.reset();
s.use_count()
void observe(const Widget& w);
std::unique_ptr<T[]> a = std::make_unique<T[]>(n);
Containers
12std::vector<int> v{1, 2, 3};
v.push_back(4); v.emplace_back(args);
v.reserve(1000);
std::map<std::string, int> m;
std::unordered_map<std::string, int> h;
m["hits"] += 1; m.at("hits");
if (m.contains(key)) ...
std::array<int, 3> a{1, 2, 3};
void f(std::span<const int> s);
std::set<int> s; std::unordered_set<int> u;
std::erase_if(v, [](int n) { return n < 0; });
v.size(); v.empty(); v.clear();
Algorithms & ranges
12std::ranges::sort(v);
std::sort(v.begin(), v.end(), cmp);
auto it = std::ranges::find_if(v, pred);
std::transform(v.begin(), v.end(), out, f);
std::accumulate(v.begin(), v.end(), 0)
std::ranges::count_if(v, pred)
v | std::views::filter(isEven)
| std::views::transform(square)
std::views::iota(0, 10)
auto v2 = r | std::ranges::to<std::vector>();
std::ranges::max_element(v)
std::ranges::any_of(v, pred)
Strings & string_view
11std::string s = "hi"; s += "!";
void f(std::string_view sv);
if (s.find("x") != std::string::npos)
s.substr(1, 3)
s.starts_with("http"); s.ends_with(".h");
s.contains("needle")
std::to_string(42)
int n = std::stoi("42");
std::format("{}: {}", key, count)
std::getline(std::cin, line);
R"(C:\path\no "escapes")"
Classes & RAII
11struct Point { int x = 0; int y = 0; };
Widget() : size_{0}, name_{"w"} {}
~Widget() { close(handle_); }
ctor, dtor, copy ctor/=, move ctor/=
Widget(const Widget&) = delete;
Widget(Widget&&) noexcept = default;
explicit Widget(int size);
int size() const { return size_; }
virtual void draw(); / void draw() override;
virtual ~Base() = default;
[[nodiscard]] bool ok() const;
Move semantics
9auto b = std::move(a);
Widget(Widget&& o) noexcept;
return result;
void set(std::string s) { s_ = std::move(s); }
v.push_back(std::move(str));
auto old = std::exchange(ptr_, nullptr);
std::swap(a, b);
// moved-from: valid but unspecified
template <class T> void f(T&& x) { g(std::forward<T>(x)); }
Templates & concepts
10template <typename T> T maxOf(T a, T b);
template <std::integral T> T half(T n);
template <class T> concept Number = std::is_arithmetic_v<T>;
void print(const auto& x);
if constexpr (std::is_integral_v<T>)
std::pair p{1, 2.5};
template <typename... Args> void log(Args&&... args);
(args + ...)
template <class T> requires Number<T> T sq(T x);
template <> struct Hash<Key> { ... };
Lambdas & std::function
10auto twice = [](int x) { return x * 2; };
[=] captures copies; [&] captures refs
[x, &total](int n) { total += x * n; }
[this] { return counter_; }
[p = std::move(ptr)] { p->run(); }
[n = 0]() mutable { return ++n; }
[](auto a, auto b) { return a < b; }
[](int x) -> double { return x / 2.0; }
std::function<int(int)> cb = twice;
std::ranges::sort(v, {}, &User::age);
Error handling
11std::optional<int> parse(std::string_view s);
opt.value_or(0)
if (opt) use(*opt);
std::expected<Data, Error> load();
res.and_then(step).transform(format)
throw std::runtime_error("bad config");
catch (const std::exception& e) { e.what(); }
void close() noexcept;
assert(ptr != nullptr);
static_assert(sizeof(int) == 4);
std::variant<int, Err> v; std::visit(fn, v);
Concurrency
10std::jthread t(work);
std::thread t(work); t.join();
std::mutex m; std::lock_guard lock(m);
std::scoped_lock lock(m1, m2);
std::unique_lock lk(m); cv.wait(lk, ready);
std::atomic<int> hits{0}; ++hits;
auto f = std::async(std::launch::async, fetch);
auto result = f.get();
std::this_thread::sleep_for(100ms);
thread_local int cache = 0;
Compilation & CMake
11g++ -std=c++23 -Wall -Wextra -O2 main.cpp -o app
clang++ -std=c++20 main.cpp -o app
-g -O0
-fsanitize=address,undefined
-Iinclude -Llib -lfoo
-DNDEBUG
cmake_minimum_required(VERSION 3.20)
add_executable(app main.cpp)
target_compile_features(app PRIVATE cxx_std_23)
cmake -B build && cmake --build build
cmake --build build -j 8
Tidak ada entri yang cocok dengan “:q”.
Tentang Lembar Contekan C++
Contekan C++ ini mengumpulkan C++ modern menjadi satu referensi yang dapat dicari: dasar dengan auto dan referensi, smart pointer, container, algoritma dan range, string dan string_view, class dan RAII, move semantics, template dan concept, lambda dan std::function, penanganan error, konkurensi, serta kompilasi dengan 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.
Seperti setiap contekan dalam grup ini, gratis dan berjalan di sisi klien: filter baris secara langsung dengan kotak pencarian, lompat antar bagian dari daftar isi yang menempel, salin cuplikan kode apa pun dengan satu klik dan cetak halaman sebagai referensi meja kerja.
Cara menggunakan Lembar Contekan C++
- Buka contekan dan tinjau bagian-bagiannya, dari Basics, auto & references hingga Compilation & CMake.
- Cari kata kunci seperti unique_ptr, ranges atau concept untuk memfilter contekan secara langsung.
- Lompat ke Move semantics atau Templates & concepts saat Anda memerlukan penjelasan sintaks yang lebih sulit.
- Klik cuplikan kode atau ikon salinnya untuk menyalin kode C++ ke clipboard Anda.
- Gunakan Cetak untuk salinan kertas dari referensi C++ lengkap.