सामग्री पर जाएँ

लेसन 162 · Practice and Review

C++ चीट शीट

एक पन्ने की आधुनिक C++ चीट शीट: टाइप, स्ट्रिंग, फ़ॉर्मैट स्पेक, कंट्रोल फ़्लो, फ़ंक्शन, लैम्ब्डा, स्मार्ट पॉइंटर, क्लास, टेम्पलेट, STL कंटेनर और रेंज।

यह पन्ना पूरे C++ कोर्स को एक सघन रेफ़रेंस में समेटता है: वह सिंटैक्स, टाइप, स्टैंडर्ड लाइब्रेरी के हिस्से और मुहावरे जिन तक आप रोज़ पहुँचते हैं, छोटे स्निपेट में जिन्हें आप सेकंडों में स्कैन कर सकते हैं। इसे खुला रखें जब आप अभ्यास प्रश्न हल करें, अपने प्रोग्राम लिखें, या इंटरव्यू से पिछली शाम।

यहाँ सब कुछ आधुनिक C++ है (C++17, C++20 और C++23, हमारे एडिटर में GCC 15 से कंपाइल)। हर भाग उस पाठ से जुड़ता है जो विषय को ठीक से समझाता है, नियमों के पीछे के कारणों के साथ। जो चीज़ें लोगों को सबसे ज़्यादा उलझाती हैं उनके साथ लाइव एडिटर हैं, ताकि आप उन्हें चलाकर ख़ुद व्यवहार देख सकें।

प्रोग्राम की बुनियादी बातें

ढाँचा, आउटपुट और इनपुट

C++
#include <print>      // std::print, std::println (C++23)
#include <iostream>   // std::cin, std::cout, std::cerr
#include <string>

int main() {
    std::println("Hello, {}!", "world");     // नई लाइन जुड़ती है
    std::print("x = {}, y = {}\n", 3, 4.5);  // नई लाइन नहीं जुड़ती
    std::cout << "classic " << 42 << '\n';   // '\n', std::endl से सस्ता है
    std::println(stderr, "errors go to stderr");

    int age{};
    std::string word, line;
    std::cin >> age >> word;          // व्हाइटस्पेस से अलग टोकन पढ़ता है
    std::cin >> std::ws;              // getline से पहले बची नई लाइन छोड़ें
    std::getline(std::cin, line);     // लाइन का बाक़ी हिस्सा पढ़ता है
    if (!std::cin) { /* इनपुट फ़ेल हुआ या फ़ाइल के अंत तक पहुँचा */ }
    return 0;                         // main में वैकल्पिक
}

हमारे एडिटर के बाहर g++ -std=c++23 -Wall -Wextra -O2 main.cpp -o app से बिल्ड करें। Getting Started, Printing Output, Reading User Input और How C++ Works देखें।

बुनियादी टाइप

टाइप सामान्य आकार उदाहरण लिटरल
bool 1 बाइट true, false
char 1 बाइट 'A', '\n'
int 4 बाइट 42, 0x2A, 0b101010, 1'000'000
long long 8 बाइट 42LL, 9'000'000'000
unsigned 4 बाइट 42u
std::size_t 8 बाइट (64-बिट) v.size(), 42uz (C++23)
float 4 बाइट 3.14f
double 8 बाइट 3.14, 1e-9
std::int32_t, std::uint8_t, … सटीक <cstdint> से

char के अलावा बाक़ी आकार इम्प्लिमेंटेशन-डिफ़ाइंड हैं; sizeof(T) और <limits> के std::numeric_limits<T>::max() से जाँचें। Fundamental Data Types, Integer Types और Floating-Point Numbers देखें।

वेरिएबल, कॉन्स्टेंट और auto

C++
int a = 5;              // कॉपी इनिशियलाइज़ेशन
int b(5);               // डायरेक्ट इनिशियलाइज़ेशन
int c{5};               // ब्रेस इनिशियलाइज़ेशन: नैरोइंग को ठुकराता है
int d{};                // वैल्यू-इनिशियलाइज़्ड, 0
int e;                  // फ़ंक्शन के भीतर UNINITIALIZED: इसे पढ़ना UB है
// int f{3.7};          // एरर: double -> int नैरोइंग

const int max_users = 100;          // इनिशियलाइज़ेशन के बाद नहीं बदल सकते
constexpr double tax = 0.21;        // कंपाइल के समय ज्ञात
constexpr int square(int x) { return x * x; }  // कंपाइल के समय इस्तेमाल योग्य
consteval int must_be_compile_time(int x) { return x + 1; }

auto n = 42;            // int
auto s = std::string{"hi"};
const auto& ref = s;    // auto const और & छोड़ देता है जब तक आप न लिखें
decltype(n) m = 0;      // "n जैसा ही टाइप"
using Score = std::uint32_t;  // टाइप अलायस (typedef से बेहतर)

Variables, Type Deduction with auto, Constants और Type Aliases देखें।

ऑपरेटर और कास्ट

C++
7 / 2        // 3     इंटीजर डिविज़न शून्य की ओर काटता है
-7 / 2       // -3
-7 % 2       // -1    शेषफल बाएँ ऑपरेंड का चिह्न लेता है
7.0 / 2      // 3.5
x += 2; x++; ++x;            // ++x कभी x++ से धीमा नहीं है
a == b; a != b; a <=> b;     // थ्री-वे तुलना (C++20)
a && b; a || b; !a;          // शॉर्ट-सर्किट
flags & mask; flags | bit; x ^ y; ~x; x << 3; x >> 1;
cond ? yes : no;

static_cast<double>(total) / count;  // वह कास्ट जो आप 99% समय इस्तेमाल करते हैं
// (double)total                     // C-स्टाइल कास्ट: बचें, यह कुछ भी कर सकता है
std::to_underlying(Color::red);      // enum class -> इंटीजर (C++23)

Arithmetic Operators, Comparison and Logical Operators, Bitwise Operators, Operator Precedence और Type Conversions and Casts देखें।

स्ट्रिंग

std::string और std::string_view

C++
std::string s = "Hello, World";
s.size();  s.empty();  s[0];  s.at(0);   // at() std::out_of_range फेंकता है
s += "!";  s.append("??");  s.push_back('.');
s.substr(7, 5);              // "World" (शुरुआत, गिनती)
s.find("o");                 // 4, या न मिलने पर std::string::npos
s.rfind('o');  s.find('o', 5);
s.replace(0, 5, "Howdy");    // (शुरुआत, गिनती, नया टेक्स्ट)
s.insert(0, ">> ");  s.erase(0, 3);
s.starts_with("He");  s.ends_with('!');  s.contains("lo");  // C++20 / C++23
s.c_str();                   // C API के लिए const char*
std::string(3, '*');         // "***"
for (char ch : s) { /* ... */ }

std::string_view view = s;   // स्वामित्व-रहित, कॉपी करना सस्ता
view.substr(0, 5);           // कोई आवंटन नहीं
void greet(std::string_view name);   // रीड-ओनली स्ट्रिंग पैरामीटर के लिए सर्वोत्तम
// string_view को कभी लोकल या अस्थायी स्ट्रिंग की ओर न लौटाएँ: वह डैंगल होगा।

रूपांतरण: std::to_string(42), std::stoi("42") और std::stod("2.5") (दोनों ग़लत इनपुट पर फेंकते हैं), या तेज़, एक्सेप्शन-रहित पार्सिंग के लिए std::from_chars। Strings, String Methods, std::string_view और Converting Between Strings and Numbers देखें।

फ़ॉर्मैट स्पेक

स्पेक कोलन के बाद आता है: {:[[fill]align][sign][#][0][width][.precision][type]}।

स्पेक उदाहरण नतीजा
चौड़ाई, दाएँ-अलाइन std::format("[{:>6}]", 42) [ 42]
बाएँ, केंद्र "ab" के साथ "[{:<6}]", "[{:^6}]" [ab ], [ ab ]
फ़िल "ab" के साथ "{:*^7}" **ab***
शून्य पैड 42 के साथ "{:05}" 00042
प्रिसिज़न 3.14159 के साथ "{:.2f}" 3.14
चिह्न 5 के साथ "{:+}" +5
हेक्स, बाइनरी 255, 5 के साथ "{:#x}", "{:08b}" 0xff, 00000101
पोज़ीशनल "a", "b" के साथ "{1} {0}" b a
रेंज (C++23) std::vector{1, 2} के साथ "{}" [1, 2]
C++ फ़ॉर्मैट स्पेक काम करते हुए

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Formatting with std::format and std::print देखें।

कंट्रोल फ़्लो

C++
if (x > 0) { /*...*/ } else if (x < 0) { /*...*/ } else { /*...*/ }
if (auto it = m.find(key); it != m.end()) { use(it->second); }  // इनिशियलाइज़र वाला if

switch (cmd) {
    case 'a': add(); break;
    case 'q': [[fallthrough]];
    case 'x': quit(); break;
    default: help();
}

for (int i = 0; i < n; ++i) { }
for (const auto& item : items) { }           // बिना कॉपी किए पढ़ें
for (auto& item : items) { item *= 2; }      // वहीं बदलें
for (auto [key, value] : my_map) { }         // स्ट्रक्चर्ड बाइंडिंग
while (std::cin >> x) { }                    // इनपुट ख़त्म होने तक लूप
do { /* कम से कम एक बार */ } while (again);
break;  continue;                            // सिर्फ़ सबसे नज़दीकी लूप

if, else if and else, switch Statements, while Loops, for Loops और break, continue and goto देखें।

फ़ंक्शन

पैरामीटर कॉपी करता है? कॉलर का ऑब्जेक्ट बदल सकता है? किसके लिए
T value हाँ नहीं छोटे टाइप (int, double, string_view), या जब आपको वैसे भी कॉपी चाहिए
const T& value नहीं नहीं बड़े रीड-ओनली इनपुट (std::string, std::vector)
T& value नहीं हाँ इन-आउट पैरामीटर
T&& value नहीं उससे मूव करता है "सिंक" ओवरलोड, परफ़ेक्ट फ़ॉरवर्डिंग
std::span<const T> नहीं नहीं कोई भी सन्निहित क्रम (ऐरे, वेक्टर)
C++
int add(int a, int b);                         // डिक्लेरेशन (प्रोटोटाइप)
int add(int a, int b) { return a + b; }        // डेफ़िनिशन
void log(std::string_view msg, int level = 1); // डिफ़ॉल्ट आर्ग्युमेंट अंत में
double area(double r);  double area(double w, double h);  // ओवरलोडिंग
auto divide(int a, int b) -> double;           // ट्रेलिंग रिटर्न टाइप

std::pair<int, int> min_max(const std::vector<int>& v);
auto [lo, hi] = min_max(values);               // स्ट्रक्चर्ड बाइंडिंग
std::optional<int> find_id(std::string_view name);  // "शायद कोई मान"
std::expected<int, std::string> parse(std::string_view text);  // मान या एरर (C++23)
[[nodiscard]] int compute();                   // नतीजा अनदेखा हो तो चेतावनी
// लोकल वेरिएबल का रेफ़रेंस या पॉइंटर कभी न लौटाएँ।

Functions, Parameters, Default Arguments, Returning Values, Function Overloading और Recursion देखें।

लैम्ब्डा

कैप्चर अर्थ
[] कुछ नहीं
[x], [=] x की कॉपी / इस्तेमाल हुई हर चीज़ की कॉपी
[&x], [&] x का रेफ़रेंस / इस्तेमाल हुई हर चीज़ का रेफ़रेंस (लाइफ़टाइम देखें)
[this], [*this] ऑब्जेक्ट पॉइंटर से / कॉपी से
[n = std::move(v)] इनिट कैप्चर: किसी एक्सप्रेशन से इनिशियलाइज़ हुआ नया मेंबर
C++
auto square = [](int x) { return x * x; };
auto counter = [count = 0]() mutable { return ++count; };  // mutable: कॉपी बदलें
auto print_any = [](const auto& value) { std::println("{}", value); };  // जेनेरिक
std::ranges::sort(people, [](const Person& a, const Person& b) { return a.age < b.age; });
const auto config = [&] { Config c; c.load(); return c; }();  // तुरंत बुलाया गया
std::function<int(int)> f = square;            // टाइप-इरेज़्ड कॉल करने योग्य (इसकी लागत है)

Lambda Expressions, Function Objects and std::function और Function Pointers देखें।

पॉइंटर, रेफ़रेंस और मेमोरी

C++
int x = 10;
int& ref = x;            // अलायस: बनते समय बाँधना होगा, दोबारा नहीं बाँधा जा सकता
int* ptr = &x;           // x का एड्रेस
*ptr = 20;               // x अब 20 है
int* nothing = nullptr;  // कभी डीरेफ़रेंस न करें
const int* p1 = &x;      // const की ओर पॉइंटर: *p1 = 1 एरर है
int* const p2 = &x;      // const पॉइंटर: p2 = other एरर है
// डिक्लेरेशन दाएँ से बाएँ पढ़ें: "p2 int की ओर एक const पॉइंटर है"।
औज़ार मालिक है? कॉपी हो सकता है? किसके लिए
T ऑब्जेक्ट / std::vector<T> हाँ हाँ डिफ़ॉल्ट: वैल्यू और कंटेनर
std::unique_ptr<T> हाँ, अकेला नहीं (सिर्फ़ मूव) एकल मालिक, पॉलीमॉर्फ़िक ऑब्जेक्ट, pimpl
std::shared_ptr<T> हाँ, साझा हाँ (रेफ़ गिनती) सचमुच साझा लाइफ़टाइम
std::weak_ptr<T> नहीं हाँ shared_ptr को देखना, चक्र तोड़ना
T*, T& नहीं हाँ आपसे ज़्यादा जीने वाली चीज़ तक स्वामित्व-रहित पहुँच
new / delete हाथ से लागू नहीं एप्लिकेशन कोड में बचें
C++ स्मार्ट पॉइंटर और स्वामित्व

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

References, Pointers, const with Pointers, Dynamic Memory, std::unique_ptr, shared_ptr and weak_ptr और Undefined Behavior देखें।

क्लास

C++
class Account {
public:
    explicit Account(std::string owner, double balance = 0)
        : owner_(std::move(owner)), balance_(balance) {}   // मेंबर इनिशियलाइज़र लिस्ट

    void deposit(double amount) {
        if (amount <= 0) { throw std::invalid_argument("amount must be positive"); }
        balance_ += amount;
    }
    double balance() const { return balance_; }            // const: बदलता नहीं
    static int count() { return count_; }

private:
    std::string owner_;
    double balance_ = 0;               // डिफ़ॉल्ट मेंबर इनिशियलाइज़र
    inline static int count_ = 0;      // क्लास पर एक, ऑब्जेक्ट पर नहीं
};

struct Point {                         // struct = पब्लिक डिफ़ॉल्ट एक्सेस वाली क्लास
    int x = 0, y = 0;
    auto operator<=>(const Point&) const = default;   // ==, <, >, ... भी देता है
};
Point p{.x = 1, .y = 2};               // डेज़िग्नेटेड इनिशियलाइज़र (C++20)

इनहेरिटेंस और पॉलीमॉर्फ़िज़्म

C++
class Shape {
public:
    virtual ~Shape() = default;              // पॉलीमॉर्फ़िक बेस को वर्चुअल डिस्ट्रक्टर चाहिए
    virtual double area() const = 0;         // प्योर वर्चुअल: Shape एब्स्ट्रैक्ट है
};

class Circle final : public Shape {
public:
    explicit Circle(double r) : r_(r) {}
    double area() const override { return std::numbers::pi * r_ * r_; }
private:
    double r_;
};

std::vector<std::unique_ptr<Shape>> shapes;
shapes.push_back(std::make_unique<Circle>(2.0));
for (const auto& s : shapes) { std::println("{:.2f}", s->area()); }
// Circle को सादे Shape वेरिएबल में कॉपी करना उसे "स्लाइस" कर देता है: पॉइंटर या रेफ़रेंस इस्तेमाल करें।

स्पेशल मेंबर फ़ंक्शन

नियम क्या कहता है
Rule of zero रिसोर्स को मेंबर (std::string, std::vector, std::unique_ptr) सँभालने दें और पाँच में से कोई न लिखें।
Rule of three अगर आप डिस्ट्रक्टर, कॉपी कंस्ट्रक्टर या कॉपी असाइनमेंट लिखते हैं, तो शायद तीनों चाहिए।
Rule of five मूव कंस्ट्रक्टर और मूव असाइनमेंट जोड़ें (उन्हें noexcept चिह्नित करें)।
= default / = delete कंपाइलर का संस्करण माँगें / ऑपरेशन मना करें।

Classes and Objects, Constructors, Destructors and RAII, Operator Overloading, Move Semantics, The Rule of Zero, Three and Five, Inheritance और Virtual Functions देखें।

Enum, struct और variant

C++
enum class Color : std::uint8_t { red, green, blue };  // स्कोप्ड: Color::red
auto c = Color::green;
switch (c) { case Color::red: /*...*/ break; default: break; }

std::variant<int, std::string> v = "text";              // टाइप-सेफ़ यूनियन
std::visit([](const auto& value) { std::println("{}", value); }, v);
std::optional<int> maybe;  maybe.value_or(0);  if (maybe) { *maybe; }

Enumerations, Structs, Aggregates and Unions और optional, variant, any and expected देखें।

टेम्पलेट और कॉन्सेप्ट

C++
template <typename T>
T biggest(T a, T b) { return a < b ? b : a; }       // biggest(3, 7), biggest<double>(3, 7.5)

auto twice(auto x) { return x + x; }                // संक्षिप्त टेम्पलेट (C++20)

template <typename T, std::size_t N>
class RingBuffer { std::array<T, N> data_{}; };    // टाइप और नॉन-टाइप पैरामीटर
RingBuffer<int, 16> buffer;

template <std::integral T>                           // कॉन्सेप्ट से सीमित
T gcd_of(T a, T b) { return b == 0 ? a : gcd_of(b, a % b); }

template <typename T>
concept Printable = requires(std::ostream& os, T value) { os << value; };

template <typename... Args>
auto sum(Args... args) { return (args + ... + 0); } // फ़ोल्ड एक्सप्रेशन

if constexpr (std::is_floating_point_v<T>) { /* सिर्फ़ फ़्लोट के लिए कंपाइल होता है */ }
static_assert(sizeof(int) >= 4, "need 32-bit int");

Function Templates, Class Templates, Concepts, Variadic Templates, Compile-Time Programming और Type Traits देखें।

STL कंटेनर

कंटेनर क्रमित? लुकअप इन्सर्ट / इरेज़ टिप्पणी
std::vector<T> पोज़ीशन से O(1) इंडेक्स अंत में O(1) एमॉर्टाइज़्ड, बीच में O(n) डिफ़ॉल्ट चुनाव
std::array<T, N> पोज़ीशन से O(1) इंडेक्स निश्चित आकार स्टैक पर रहता है
std::deque<T> पोज़ीशन से O(1) इंडेक्स दोनों सिरों पर O(1)
std::list<T> पोज़ीशन से O(n) इटरेटर के साथ O(1) स्थिर इटरेटर, चलने में धीमी
std::map<K, V> क्रमित कुंजियाँ O(log n) O(log n) रेड-ब्लैक ट्री
std::unordered_map<K, V> नहीं O(1) औसत O(1) औसत हैश टेबल
std::set<T> / std::unordered_set<T> क्रमित / नहीं O(log n) / O(1) औसत वही अद्वितीय कुंजियाँ
std::stack, std::queue एडाप्टर top / front O(1) डिफ़ॉल्ट रूप से deque को लपेटते हैं
std::priority_queue<T> हीप O(1) top O(log n) डिफ़ॉल्ट रूप से मैक्स-हीप
C++
std::vector<int> v{3, 1, 4};
v.push_back(1);  v.emplace_back(5);  v.pop_back();
v.reserve(100);  v.size();  v.capacity();  v.front();  v.back();
v.insert(v.begin() + 1, 9);  v.erase(v.begin());
std::erase(v, 4);  std::erase_if(v, [](int x) { return x > 3; });  // C++20

std::map<std::string, int> ages{{"Ana", 31}};
ages["Ben"] = 25;              // कुंजी न होने पर operator[] डिफ़ॉल्ट मान INSERT करता है
ages.try_emplace("Cy", 40);    // सिर्फ़ अनुपस्थित होने पर डालता है
ages.contains("Ana");          // C++20
if (auto it = ages.find("Dee"); it != ages.end()) { /*...*/ }
for (const auto& [name, age] : ages) { }   // कुंजी के क्रम में

std::priority_queue<int, std::vector<int>, std::greater<>> min_heap;  // सबसे छोटा ऊपर

The Standard Template Library, std::vector, std::array, std::map, std::unordered_map, std::set, Container Adapters और Iterators देखें।

एल्गोरिदम और रेंज

C++
#include <algorithm>   // sort, find, count, ...
#include <numeric>     // accumulate, iota, reduce, ...
#include <ranges>      // views

std::ranges::sort(v);                         // बढ़ते क्रम में
std::ranges::sort(v, std::greater{});         // घटते क्रम में
std::ranges::sort(people, {}, &Person::age);  // किसी मेंबर से ("प्रोजेक्शन")
std::ranges::find(v, 42);                     // इटरेटर, या v.end()
std::ranges::count_if(v, is_even);
std::ranges::max_element(v);  std::ranges::minmax(v);
std::ranges::binary_search(sorted, 7);        // क्रमित इनपुट चाहिए
std::ranges::reverse(v);  std::ranges::unique(v);  std::ranges::fill(v, 0);
std::ranges::any_of(v, pred);  std::ranges::all_of(v, pred);
std::accumulate(v.begin(), v.end(), 0);       // योग; double के लिए 0.0 इस्तेमाल करें!
std::iota(v.begin(), v.end(), 1);             // 1, 2, 3, ...

auto evens_squared = v | std::views::filter(is_even)
                       | std::views::transform([](int x) { return x * x; });
auto result = evens_squared | std::ranges::to<std::vector>();   // C++23
C++ रेंज पाइपलाइन

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Algorithms: Searching, Sorting and Counting, Algorithms: Transforming and Modifying, Numeric Algorithms और Ranges and Views देखें।

एरर

C++
try {
    auto n = std::stoi(text);
    if (n < 0) { throw std::out_of_range("negative"); }
} catch (const std::invalid_argument& e) {    // const रेफ़रेंस से पकड़ें
    std::println("not a number: {}", e.what());
} catch (const std::exception& e) {           // बेस क्लास सबसे बाद
    std::println("error: {}", e.what());
}

class ConfigError : public std::runtime_error {
public:
    using std::runtime_error::runtime_error;   // कंस्ट्रक्टर इनहेरिट करें
};

void swap_fast(Buffer& other) noexcept;        // न फेंकने का वादा
assert(index < size);                          // <cassert>, -DNDEBUG से हट जाता है
तरीक़ा कब इस्तेमाल करें
एक्सेप्शन एरर दुर्लभ हों और अनदेखे नहीं होने चाहिए; ऐसे कंस्ट्रक्टर जो फ़ेल हो सकते हैं
std::optional<T> "कोई नतीजा नहीं" सामान्य हो और उसे स्पष्टीकरण न चाहिए
std::expected<T, E> (C++23) कॉलर को विफलता सँभालनी चाहिए और कारण जानना चाहिए
assert / static_assert डेवलपमेंट के दौरान / कंपाइल के समय प्रोग्रामर की ग़लतियाँ पकड़ना

Exceptions, Custom Exception Classes, Exception Safety and noexcept, Error Handling Without Exceptions और Assertions and Debugging देखें।

फ़ाइलें और स्ट्रीम

C++
#include <fstream>
#include <sstream>
#include <filesystem>
namespace fs = std::filesystem;

std::ofstream out("notes.txt");               // जोड़ने के लिए std::ios::app
out << "line one\n";
std::ifstream in("notes.txt");
if (!in) { /* खोल नहीं सके */ }
for (std::string line; std::getline(in, line); ) { }
// स्ट्रीम ऑब्जेक्ट नष्ट होने पर फ़ाइलें अपने आप बंद होती हैं (RAII)।

std::istringstream parts("10 20 30");
int total = 0;
for (int n; parts >> n; ) { total += n; }

fs::exists("notes.txt");  fs::file_size("notes.txt");
fs::create_directories("out/logs");
for (const auto& entry : fs::directory_iterator(".")) { entry.path().filename(); }

I/O Streams in Depth, Reading and Writing Text Files, String Streams और The Filesystem Library देखें।

यूटिलिटी और कॉन्करेंसी

C++
using namespace std::chrono_literals;
auto start = std::chrono::steady_clock::now();
auto elapsed = std::chrono::steady_clock::now() - start;
std::println("{}", std::chrono::duration_cast<std::chrono::milliseconds>(elapsed));

std::mt19937 gen{std::random_device{}()};
std::uniform_int_distribution<int> dice{1, 6};
int roll = dice(gen);

std::jthread worker([](std::stop_token st) { while (!st.stop_requested()) { /*...*/ } });
std::mutex m;
{ std::scoped_lock lock(m); /* एक समय में एक थ्रेड */ }
std::atomic<int> hits{0};  hits.fetch_add(1);  hits++;
auto future = std::async(std::launch::async, [] { return 42; });
int answer = future.get();                     // इंतज़ार करता है; टास्क का एक्सेप्शन दोबारा फेंकता है

chrono, Random Numbers, Threads, Mutexes and Locks, Atomics और std::async, Futures and Promises देखें।

याद रखने लायक जाल

  • साइन्ड और अनसाइन्ड मानों की तुलना साइन्ड वाले को कन्वर्ट करती है: -1 < 1u false है।
  • std::accumulate(v.begin(), v.end(), 0) double का योग int की तरह करता है। 0.0 से शुरू करें।
  • map[key] कुंजी न होने पर डिफ़ॉल्ट मान डालता है, भले ही आपका मतलब सिर्फ़ पढ़ना था।
  • साइन्ड इंटीजर ओवरफ़्लो, सीमा से बाहर इंडेक्सिंग और use-after-free अनडिफ़ाइंड बिहेवियर हैं: प्रोग्राम काम करता लग सकता है, फिर कहीं और फ़ेल हो सकता है।
  • std::vector में जोड़ने से रीअलोकेशन हो सकता है और उसके भीतर के हर इटरेटर, पॉइंटर और रेफ़रेंस अमान्य हो सकते हैं।
  • std::vector<bool> बिट पैक करता है और असली bool ऑब्जेक्ट नहीं रखता; auto& b = flags[0] कंपाइल नहीं होता।
  • वर्चुअल डिस्ट्रक्टर के बिना बेस क्लास तब लीक या करप्ट होती है जब आप बेस पॉइंटर से डिराइव्ड ऑब्जेक्ट को delete करते हैं।
C++ जाल जो आप चलाकर देख सकते हैं

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

पहली लाइन true प्रिंट करती है क्योंकि int में कास्ट तुलना को साइन्ड रखता है; दूसरी दिखाती है कि जब -1 अनसाइन्ड संख्या (4294967295) बन जाता है तब क्या होता है। 0 के साथ accumulate कॉल हर आंशिक योग को int में काट देता है, इसलिए वह 7.5 की जगह 6 प्रिंट करता है। ऐसे और जालों के लिए Best Practices and Common Mistakes देखें।

अपनी समझ जाँचें

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. std::println("{:>5}|{:<5}|", 42, 7); क्या प्रिंट करता है?

    5, 42 को 5 कैरेक्टर के फ़ील्ड में दाएँ-अलाइन करता है (पहले तीन स्पेस), और <5, 7 को बाएँ-अलाइन करता है और उसके बाद चार स्पेस आते हैं।

  2. 2. आप ऐसे std::map पर ages["Zed"] कॉल करते हैं जिसमें कुंजी "Zed" नहीं है। क्या होता है?

    operator[] हमेशा किसी एलिमेंट का रेफ़रेंस लौटाता है, इसलिए कुंजी न होने पर वह एक बना देता है। बिना डाले पढ़ने के लिए find(), contains() या at() इस्तेमाल करें।
  3. 3. जिस ऑब्जेक्ट का एक समय में ठीक एक मालिक हो, उसके लिए कौन-सा स्मार्ट पॉइंटर उपयुक्त है?

    unique_ptr शून्य ओवरहेड पर अनन्य स्वामित्व दर्शाता है और उसे ट्रांसफ़र करने के लिए मूव किया जा सकता है। shared_ptr रेफ़रेंस काउंटिंग जोड़ता है जिसकी आपको ज़रूरत नहीं।
  4. 4. C++ में -7 / 2 और -7 % 2 का मान क्या है?

    इंटीजर डिविज़न शून्य की ओर काटता है, जिससे -3 मिलता है, और शेषफल बाएँ ऑपरेंड का चिह्न लेता है, इसलिए (-3 * 2) + (-1) == -7।

सारांश

  • std::println और फ़ॉर्मैट स्पेक से प्रिंट करें; std::cin >> और std::getline से पढ़ें, और जाँचें कि इनपुट सफल रहा।
  • सब कुछ इनिशियलाइज़ करें, ब्रेस इनिशियलाइज़ेशन को तरजीह दें, और जो मान नहीं बदलते उनके लिए const/constexpr इस्तेमाल करें।
  • बड़े रीड-ओनली इनपुट const& से (या std::string_view/std::span से) दें, नतीजे वैल्यू से लौटाएँ, और जो नतीजे ग़ायब हो सकते हैं उनके लिए std::optional या std::expected इस्तेमाल करें।
  • मेमोरी का स्वामित्व वैल्यू, कंटेनर और std::unique_ptr से रखें; std::shared_ptr सिर्फ़ सचमुच साझा लाइफ़टाइम के लिए लें।
  • डिफ़ॉल्ट रूप से std::vector लें, लुकअप के लिए मैप और सेट इस्तेमाल करें, और लूपिंग का काम एल्गोरिदम और रेंज को करने दें।
  • क्लासिक जाल याद रखें: साइन्ड/अनसाइन्ड तुलना, map[] का इन्सर्ट करना, इटरेटर अमान्य होना और अनडिफ़ाइंड बिहेवियर।

अगला पाठ: C++ Programs: 40 Classic Examples, जहाँ आप इन औज़ारों को छोटे, पूरे प्रोग्राम में काम करते देखेंगे।

अपनी प्रगति ट्रैक करें

मुफ़्त अकाउंट बनाएँ, लेसन पूरे के रूप में चिह्नित करें और किसी भी डिवाइस पर वहीं से शुरू करें जहाँ छोड़ा था।