Classes, templates, STL, smart pointers, RAII & modern C++ features
Language#include <iostream>
using namespace std;
int main() {
cout << "Hello World" << endl;
return 0;
}
// Variables
auto x = 42; // type deduction (C++11)
int a{10}; // uniform initialization
const auto PI = 3.14;
constexpr int N = 100; // compile-time constant
// References
int val = 5;
int& ref = val; // lvalue reference
int&& rref = 42; // rvalue reference (C++11)
// Range-based for
vector<int> v = {1,2,3};
for (auto& x : v) cout << x;
// Structured bindings (C++17)
auto [key, value] = make_pair(1, "hello");class Animal {
private:
string name;
int age;
public:
// Constructor
Animal(string n, int a) : name(move(n)), age(a) {}
// Copy constructor
Animal(const Animal& other) = default;
// Move constructor (C++11)
Animal(Animal&& other) noexcept = default;
// Virtual destructor for polymorphism
virtual ~Animal() = default;
// Virtual method
virtual string speak() const { return "..."; }
// Getter
string getName() const { return name; }
};
class Dog : public Animal {
public:
using Animal::Animal;
string speak() const override { return "Woof!"; }
};#include <vector>
#include <map>
#include <set>
#include <unordered_map>
#include <queue>
#include <stack>
// vector — dynamic array
vector<int> v = {1,2,3};
v.push_back(4); v.pop_back();
v.size(); v.empty();
v[0]; v.at(0); // bounds-checked
v.begin(); v.end();
v.insert(v.begin()+1, 99);
v.erase(v.begin());
// map — sorted key-value (O(log n))
map<string, int> m;
m["a"] = 1;
m.count("a"); // 1 if exists
m.find("a"); // iterator
for (auto& [k,v] : m) cout << k << v;
// unordered_map — hash map (O(1) avg)
unordered_map<string, int> um;
// set — sorted unique values
set<int> s = {3,1,2}; // stored as {1,2,3}
s.insert(4); s.erase(2); s.count(1);
// stack & queue
stack<int> st; st.push(1); st.top(); st.pop();
queue<int> q; q.push(1); q.front(); q.pop();
priority_queue<int> pq; // max-heap#include <algorithm>
#include <numeric>
vector<int> v = {4,2,7,1,9};
sort(v.begin(), v.end()); // ascending
sort(v.begin(), v.end(), greater<int>()); // descending
reverse(v.begin(), v.end());
auto it = find(v.begin(), v.end(), 7);
binary_search(v.begin(), v.end(), 7); // true/false
int mx = *max_element(v.begin(), v.end());
int mn = *min_element(v.begin(), v.end());
int sum = accumulate(v.begin(), v.end(), 0);
int cnt = count(v.begin(), v.end(), 7);
// Transform
transform(v.begin(), v.end(), v.begin(),
[](int x){ return x * 2; });
// Remove-erase idiom
v.erase(remove_if(v.begin(), v.end(),
[](int x){ return x < 5; }), v.end());
// Unique (sorted first!)
v.erase(unique(v.begin(), v.end()), v.end());#include <memory>
// unique_ptr — exclusive ownership
auto p1 = make_unique<int>(42);
auto p2 = make_unique<int[]>(10); // array
*p1 = 100;
auto p3 = move(p1); // transfer ownership (p1 is null)
// shared_ptr — reference-counted
auto sp1 = make_shared<string>("hello");
auto sp2 = sp1; // ref count = 2
sp1.use_count(); // 2
sp1.reset(); // release, count = 1
// weak_ptr — non-owning observer
weak_ptr<string> wp = sp2;
if (auto locked = wp.lock()) {
cout << *locked; // safe access
}
// Rule of 5: If you define any of these, define all:
// destructor, copy ctor, copy=, move ctor, move=// Function template
template<typename T>
T maximum(T a, T b) { return (a > b) ? a : b; }
maximum(3, 7); // int
maximum(3.5, 7.2); // double
// Class template
template<typename T, int N>
class Array {
T data[N];
public:
T& operator[](int i) { return data[i]; }
constexpr int size() const { return N; }
};
Array<int, 5> arr;
// Variadic templates (C++11)
template<typename... Args>
void print(Args... args) {
(cout << ... << args) << endl; // fold expression C++17
}
// Concepts (C++20)
template<typename T>
concept Numeric = is_arithmetic_v<T>;
template<Numeric T>
T add(T a, T b) { return a + b; }// std::optional (C++17)
optional<int> find(int id) {
if (id > 0) return id * 10;
return nullopt;
}
auto val = find(5);
if (val) cout << *val;
val.value_or(0);
// std::variant (C++17)
variant<int, string> v = "hello";
get<string>(v); // "hello"
holds_alternative<int>(v); // false
// std::any (C++17)
any a = 42;
any_cast<int>(a);
// if-init (C++17)
if (auto it = m.find("key"); it != m.end()) {
cout << it->second;
}
// Coroutines (C++20)
// Ranges (C++20)
auto result = v | views::filter([](int n){ return n%2==0; })
| views::transform([](int n){ return n*n; });
// std::format (C++20)
string s = format("Hello {} you are {}", "Alice", 30);#include <string>
#include <sstream>
string s = "Hello World";
s.length(); s.size(); s.empty();
s.substr(6, 5); // "World"
s.find("World"); // 6 (npos if not found)
s.replace(0, 5, "Hi"); // "Hi World"
s.append("!");
s += " again";
s.erase(0, 3);
stoi("42"); stod("3.14"); to_string(42);
// String stream
stringstream ss;
ss << "Age: " << 25;
string result = ss.str();
// File I/O
#include <fstream>
ofstream out("file.txt");
out << "Hello" << endl;
out.close();
ifstream in("file.txt");
string line;
while (getline(in, line)) cout << line;// Basic lambda
auto add = [](int a, int b) { return a + b; };
add(3, 4); // 7
// Capture modes
int x = 10, y = 20;
[=]() { return x + y; } // capture all by value
[&]() { x++; y++; } // capture all by reference
[x, &y]() { y = x; } // x by value, y by ref
[&, x]() { } // all by ref except x by value
// Generic lambda (C++14)
auto print = [](auto x) { cout << x; };
// Mutable lambda
auto counter = [n=0]() mutable { return n++; };
// Lambda with STL
sort(v.begin(), v.end(), [](int a, int b) {
return a > b; // descending
});
// Immediately invoked
auto val = []() { return 42; }();// RAII — Resource Acquisition Is Initialization
// Resources tied to object lifetime
class FileGuard {
FILE* fp;
public:
FileGuard(const char* path) : fp(fopen(path, "r")) {}
~FileGuard() { if(fp) fclose(fp); }
FILE* get() { return fp; }
};
// Move semantics
vector<int> create() {
vector<int> v = {1,2,3};
return v; // moved, not copied (RVO)
}
// emplace vs push (in-place construction)
vector<string> v;
v.push_back(string("hello")); // construct + move
v.emplace_back("hello"); // construct in-place (faster)
// Compile: g++ -std=c++20 -Wall -O2 -o prog main.cpp