C++ Documentation
Fast, powerful and the favourite for DSA and competitive programming — with OOP, templates and the STL.
C++ extends C with classes, templates and a huge Standard Template Library (STL). It is fast like C but far more expressive, which is why it is the top choice for competitive programming, DSA interviews, game engines, browsers and high-performance systems.
1. Introduction & Installation
C++ files (.cpp) are compiled to a native executable.
- Windows: install MSYS2 and run
pacman -S mingw-w64-ucrt-x86_64-gcc(addsg++), or use Visual Studio. - macOS:
xcode-select --install(clang++). - Linux:
sudo apt install build-essential.
g++ --version
g++ -std=c++17 -O2 -Wall main.cpp -o main
./main
#include <iostream>
using namespace std;
int main() {
cout << "Hello, Codify!" << endl;
return 0;
}
Output:
Hello, Codify!
⚠️ Common error:
'cout' was not declared in this scope— add#include <iostream>and eitherusing namespace std;or writestd::cout.
2. Basic Syntax
- Execution starts in
main(); statements end with;; blocks use{ }. cin >>reads input,cout <<prints.endl(or"\n") ends the line.- Comments:
//and/* ... */. - In competitive programming people often use
#include <bits/stdc++.h>(GCC only) to include everything.
#include <iostream>
using namespace std;
int main() {
int a, b;
cin >> a >> b;
cout << "Sum: " << a + b << "\n";
cout << "Product: " << a * b << "\n";
return 0;
}
Output (input 6 7):
Sum: 13
Product: 42
💡 Tip: for big inputs add
ios::sync_with_stdio(false); cin.tie(nullptr);at the top ofmain— it makescin/coutmuch faster.
Practice: Read your name with getline(cin, name) and greet the user.
3. Variables & Data Types
| Type | Size (typical) | Range / use |
|---|---|---|
bool |
1 byte | true / false |
char |
1 byte | a character |
int |
4 bytes | about ±2.1 × 10⁹ |
long long |
8 bytes | about ±9.2 × 10¹⁸ |
double |
8 bytes | decimals (~15 digits) |
string |
— | text (#include <string>) |
auto |
— | let the compiler infer the type |
#include <iostream>
#include <string>
#include <climits>
#include <iomanip>
using namespace std;
int main() {
int age = 21;
long long views = 5000000000LL;
double price = 49.999;
char grade = 'A';
bool ok = true;
string name = "Codify";
auto total = age + 0.5; // double
cout << age << " " << views << " " << grade << " " << ok << " " << name << "\n";
cout << fixed << setprecision(2) << price << " " << total << "\n";
cout << INT_MAX << " " << LLONG_MAX << "\n";
return 0;
}
Output:
21 5000000000 A 1 Codify
50.00 21.50
2147483647 9223372036854775807
⚠️ Common error:
intoverflow ina * bwhen the answer exceeds ~2.1 × 10⁹. Uselong long(and cast before multiplying:1LL * a * b).
4. Operators
C++ has the same operators as C — arithmetic + - * / %, comparison, logical && || !, bitwise & | ^ ~ << >>, ++/--, compound assignment and the ternary ?: — plus :: (scope), new/delete and operator overloading for your own types.
#include <iostream>
using namespace std;
int main() {
int a = 17, b = 5;
cout << a / b << " " << a % b << " " << (double)a / b << "\n";
cout << (a > b && b > 0) << " " << !(a == 17) << "\n";
cout << (a & 1 ? "odd" : "even") << "\n";
cout << (1 << 10) << " " << __builtin_popcount(13) << "\n"; // 13 = 1101b
return 0;
}
Output:
3 2 3.4
1 0
odd
1024 3
⚠️ Common error:
cout << a & 1;—<<binds tighter than&. Use brackets:cout << (a & 1);.
5. Conditional Statements
#include <iostream>
using namespace std;
int main() {
int n = -4;
if (n > 0) cout << "positive\n";
else if (n < 0) cout << "negative\n";
else cout << "zero\n";
char op = '*';
int x = 6, y = 3;
switch (op) {
case '+': cout << x + y << "\n"; break;
case '-': cout << x - y << "\n"; break;
case '*': cout << x * y << "\n"; break;
default: cout << "unknown\n";
}
cout << (n % 2 == 0 ? "even" : "odd") << "\n";
return 0;
}
Output:
negative
18
even
⚠️ Common error: missing
breakinswitchcauses fall-through into the next case.
6. Loops
#include <iostream>
#include <vector>
using namespace std;
int main() {
for (int i = 1; i <= 5; i++) cout << i * i << " ";
cout << "\n";
vector<int> v = {3, 1, 4, 1, 5};
int sum = 0;
for (int x : v) sum += x; // range-based for
cout << "sum = " << sum << "\n";
int n = 100, steps = 0;
while (n != 1) { // Collatz steps
n = (n % 2 == 0) ? n / 2 : 3 * n + 1;
steps++;
}
cout << "steps = " << steps << "\n";
return 0;
}
Output:
1 4 9 16 25
sum = 14
steps = 25
break exits the loop, continue skips to the next iteration. Use for (auto &x : v) to modify elements in place.
⚠️ Common error: comparing
int iwithv.size()(unsigned) —for (int i = 0; i < v.size() - 1; i++)breaks whenvis empty because0 - 1wraps to a huge number. Cast:(int)v.size() - 1.
7. Functions
#include <iostream>
#include <vector>
using namespace std;
int add(int a, int b = 10) { return a + b; } // default argument
double add(double a, double b) { return a + b; } // overloading
void doubleIt(int &x) { x *= 2; } // pass by reference
int sumOf(const vector<int> &v) { // const ref: no copy
int s = 0;
for (int x : v) s += x;
return s;
}
long long power(long long b, int e) { // recursion (fast power)
if (e == 0) return 1;
long long half = power(b, e / 2);
return e % 2 ? half * half * b : half * half;
}
int main() {
int x = 7;
doubleIt(x);
cout << add(5) << " " << add(2.5, 1.25) << " " << x << "\n";
cout << sumOf({1, 2, 3, 4}) << " " << power(2, 40) << "\n";
auto square = [](int n) { return n * n; }; // lambda
cout << square(9) << "\n";
return 0;
}
Output:
15 3.75 14
10 1099511627776
81
⚠️ Common error: passing a big
vectorby value copies it on every call (slow, may TLE). Passconst vector<int>&instead.
8. Arrays & Data Structures
The STL gives you ready-made containers and algorithms:
| Container | Use | Key operations |
|---|---|---|
vector<T> |
dynamic array | push_back, [], size — O(1) |
string |
text | +, substr, find |
pair<A,B> |
two values | .first, .second |
stack<T> / queue<T> |
LIFO / FIFO | push, pop, top/front |
priority_queue<T> |
heap (max by default) | push, top, pop — O(log n) |
set<T> / map<K,V> |
sorted, unique | insert, find, count — O(log n) |
unordered_set / unordered_map |
hash table | O(1) average |
deque<T> |
double-ended queue | push_front, push_back |
#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <algorithm>
#include <unordered_map>
using namespace std;
int main() {
vector<int> v = {5, 2, 9, 1, 7};
sort(v.begin(), v.end());
v.push_back(10);
cout << v.front() << " " << v.back() << " " << v.size() << "\n";
cout << binary_search(v.begin(), v.end(), 7) << " "
<< (lower_bound(v.begin(), v.end(), 6) - v.begin()) << "\n";
cout << *max_element(v.begin(), v.end()) << "\n";
map<string, int> marks = {{"ravi", 78}, {"asha", 91}};
marks["neha"] = 85;
for (auto &p : marks) cout << p.first << ":" << p.second << " "; // sorted by key
cout << "\n";
unordered_map<char, int> freq;
for (char c : string("banana")) freq[c]++;
cout << "a=" << freq['a'] << " n=" << freq['n'] << "\n";
set<int> s = {4, 1, 4, 2};
cout << s.size() << " " << *s.begin() << "\n";
stack<int> st; st.push(1); st.push(2); cout << st.top() << " ";
queue<int> q; q.push(1); q.push(2); cout << q.front() << " ";
priority_queue<int> pq; for (int x : {3, 8, 5}) pq.push(x); cout << pq.top() << "\n";
return 0;
}
Output:
1 10 6
1 3
10
asha:91 neha:85 ravi:78
a=3 n=2
3 1
2 1 8
For a min-heap use priority_queue<int, vector<int>, greater<int>>. A 2-D grid: vector<vector<int>> g(n, vector<int>(m, 0));.
⚠️ Common error:
map[key]creates the key (with value 0) if it doesn't exist. Usecount(key)orfind(key)just to check.
9. Object-Oriented Programming
#include <iostream>
#include <string>
#include <vector>
#include <memory>
using namespace std;
class Shape { // abstract base class
public:
virtual double area() const = 0; // pure virtual
virtual string name() const { return "shape"; }
virtual ~Shape() = default; // virtual destructor
};
class Rectangle : public Shape { // inheritance
double w, h; // private by default
public:
Rectangle(double w, double h) : w(w), h(h) {}
double area() const override { return w * h; }
string name() const override { return "rectangle"; }
};
class Circle : public Shape {
double r;
public:
explicit Circle(double r) : r(r) {}
double area() const override { return 3.14159 * r * r; }
string name() const override { return "circle"; }
};
int main() {
vector<unique_ptr<Shape>> shapes;
shapes.push_back(make_unique<Rectangle>(3, 4));
shapes.push_back(make_unique<Circle>(1));
for (auto &s : shapes) cout << s->name() << " " << s->area() << "\n"; // polymorphism
return 0;
}
Output:
rectangle 12
circle 3.14159
Key ideas: encapsulation (private/protected/public), constructors/destructors (RAII — resources are released automatically in the destructor), inheritance, runtime polymorphism via virtual functions, operator overloading (Point operator+(const Point&)), static members and friend functions.
⚠️ Common error: deleting a derived object through a base pointer without a
virtualdestructor leaks resources. Make base destructors virtual.
10. Advanced Concepts
Templates write code once for any type:
#include <iostream>
#include <string>
using namespace std;
template <typename T>
T maxOf(T a, T b) { return a > b ? a : b; }
template <typename T>
class Box {
T value;
public:
Box(T v) : value(v) {}
T get() const { return value; }
};
int main() {
cout << maxOf(3, 9) << " " << maxOf(2.5, 1.5) << " " << maxOf<string>("apple", "mango") << "\n";
Box<int> b(42);
cout << b.get() << "\n";
return 0;
}
9 2.5 mango
42
Exception handling:
#include <iostream>
#include <stdexcept>
using namespace std;
double divide(double a, double b) {
if (b == 0) throw invalid_argument("division by zero");
return a / b;
}
int main() {
try {
cout << divide(10, 4) << "\n";
cout << divide(1, 0) << "\n";
} catch (const invalid_argument &e) {
cout << "Error: " << e.what() << "\n";
}
return 0;
}
2.5
Error: division by zero
Pointers, references and smart pointers — prefer unique_ptr/shared_ptr (<memory>) over raw new/delete. Other topics: move semantics (std::move), const correctness, iterators, STL algorithms (sort with a lambda comparator, accumulate, next_permutation), <chrono>, and threads (<thread>, <mutex>).
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
using namespace std;
int main() {
vector<pair<string, int>> people = {{"Ravi", 25}, {"Asha", 21}, {"Neha", 25}};
sort(people.begin(), people.end(), [](const auto &a, const auto &b) {
if (a.second != b.second) return a.second > b.second; // age desc
return a.first < b.first; // then name asc
});
for (auto &p : people) cout << p.first << " ";
vector<int> v = {1, 2, 3, 4};
cout << "| " << accumulate(v.begin(), v.end(), 0) << "\n";
return 0;
}
Neha Ravi Asha | 10
⚠️ Common error: returning a reference or pointer to a local variable — it is destroyed when the function returns (dangling reference).
11. Examples with Output
Example 1 — Two Sum with unordered_map
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
vector<int> twoSum(const vector<int> &nums, int target) {
unordered_map<int, int> seen;
for (int i = 0; i < (int)nums.size(); i++) {
auto it = seen.find(target - nums[i]);
if (it != seen.end()) return {it->second, i};
seen[nums[i]] = i;
}
return {};
}
int main() {
auto r = twoSum({2, 7, 11, 15}, 9);
cout << r[0] << " " << r[1] << "\n";
return 0;
}
0 1
Example 2 — Kadane's maximum subarray sum
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> a = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
long long best = a[0], cur = 0;
for (int x : a) {
cur = max<long long>(x, cur + x);
best = max(best, cur);
}
cout << best << "\n";
return 0;
}
6
Example 3 — BFS on a graph
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
int main() {
int n = 6;
vector<vector<int>> adj(n);
auto edge = [&](int u, int v) { adj[u].push_back(v); adj[v].push_back(u); };
edge(0, 1); edge(0, 2); edge(1, 3); edge(2, 4); edge(4, 5);
vector<int> dist(n, -1);
queue<int> q;
q.push(0); dist[0] = 0;
while (!q.empty()) {
int u = q.front(); q.pop();
for (int v : adj[u]) if (dist[v] == -1) { dist[v] = dist[u] + 1; q.push(v); }
}
for (int d : dist) cout << d << " ";
cout << "\n";
return 0;
}
0 1 1 2 2 3
12. Practice Problems
Solve these on Codify (choose C++ in the editor):
- Sum of Two Numbers —
long long(Easy) - Reverse a String —
reverse(s.begin(), s.end())(Easy) - Two Sum —
unordered_map(Easy) - Binary Search — or
lower_bound(Easy) - Valid Parentheses —
stack<char>(Medium) - Maximum Subarray Sum — Kadane (Medium)
- Longest Common Subsequence — 2-D DP table (Medium)
- Edit Distance — classic DP (Hard)
Then follow the full Codify DSA Sheet — arrays, strings, recursion, linked lists, trees, graphs and DP.
13. Interview Questions
1. What is the difference between C and C++? C is procedural; C++ adds classes, templates, references, exceptions, namespaces, function overloading and the STL.
2. Pointer vs reference? A reference is an alias that must be initialised and cannot be re-seated or null; a pointer stores an address, can be null and can point elsewhere later.
3. What is a virtual function? A member function resolved at runtime through the vtable, so a base-class pointer calls the derived class's override (runtime polymorphism).
4. What is RAII? "Resource Acquisition Is Initialization": tie resources (memory, files, locks) to object lifetime so destructors release them automatically.
5. vector vs array vs list?
Arrays have fixed size; vector is a resizable contiguous array (fast random access); list is a doubly linked list (fast insert/erase anywhere, no random access).
6. map vs unordered_map?
map is a balanced BST — sorted keys, O(log n). unordered_map is a hash table — O(1) average, no order, worst case O(n).
7. What are unique_ptr and shared_ptr?
Smart pointers: unique_ptr has single ownership; shared_ptr uses reference counting and frees the object when the last owner goes away.
8. What is the Rule of Three/Five? If a class needs a custom destructor, copy constructor or copy assignment, it probably needs all three — plus move constructor and move assignment in C++11 (five).
9. Function overloading vs overriding? Overloading: same name, different parameters (compile time). Overriding: a derived class redefines a virtual function (runtime).
10. What does const after a member function mean?
int get() const promises not to modify the object, so it can be called on const objects.
14. Cheat Sheet & References
Template for competitive programming
#include <bits/stdc++.h>
using namespace std;
int main() { ios::sync_with_stdio(false); cin.tie(nullptr); }
// Compile with C++17 and warnings
// g++ -std=c++17 -O2 -Wall main.cpp -o main
Input / output
int n; cin >> n;
vector<int> a(n); for (auto &x : a) cin >> x;
string line; getline(cin, line);
cout << x << " " << y << "\n";
cout << fixed << setprecision(6) << d << "\n";
Vector and string
vector<int> v(n, 0); v.push_back(x); v.pop_back();
v.size(); v.empty(); v.clear(); v.back();
sort(v.begin(), v.end()); reverse(v.begin(), v.end());
vector<vector<int>> g(n, vector<int>(m));
s.size(); s.substr(i, len); s.find("ab"); s += "x";
to_string(42); stoi("42"); stoll("9000000000");
Maps, sets, heaps
map<string, int> m; m["a"]++; m.count("a"); m.erase("a");
unordered_map<int, int> h; h.reserve(1 << 20);
set<int> s; s.insert(x); s.find(x) != s.end(); s.erase(x);
priority_queue<int> maxh;
priority_queue<int, vector<int>, greater<int>> minh;
stack<int> st; queue<int> q; deque<int> dq;
Algorithms
lower_bound(v.begin(), v.end(), x) - v.begin();
upper_bound(v.begin(), v.end(), x) - v.begin();
*max_element(v.begin(), v.end()); *min_element(v.begin(), v.end());
accumulate(v.begin(), v.end(), 0LL);
sort(v.begin(), v.end(), [](int a, int b) { return a > b; });
next_permutation(v.begin(), v.end());
__gcd(a, b); __builtin_popcount(x);
Classes
class A { public: A(int x) : x(x) {} virtual ~A() = default; private: int x; };
class B : public A { public: B() : A(0) {} };
auto p = make_unique<B>();
Official documentation