CPP Programming

This C++ cheatsheet provides a quick

Complete C++ Programming Cheatsheet

A comprehensive reference guide to C++ programming, covering fundamental concepts, syntax, data types, operators, control structures, arrays, strings, functions, pointers, object-oriented programming, inheritance, polymorphism, STL, file handling, exception handling, and advanced C++ concepts.

1. Introduction to C++

C++ is a general-purpose, compiled programming language developed by Bjarne Stroustrup at Bell Laboratories. It was initially known as C with Classes.

C++ supports procedural, object-oriented, and generic programming.

Features of C++

Applications of C++

File Extensions

ExtensionDescription
.cppC++ source file
.ccC++ source file
.cxxC++ source file
.hHeader file
.hppC++ header file
.oObject file
.exeWindows executable

2. Structure of a C++ Program

#include <iostream> using namespace std; int main() { cout << "Hello, World!"; return 0; }

Explanation

ComponentDescription
#includeIncludes header files
<iostream>Input/output stream library
using namespace stdMakes standard namespace names available
int main()Main function
{ }Defines a block
coutDisplays output
return 0Indicates successful execution
;Terminates a statement

Compilation Using GCC

g++ program.cpp -o program ./program

Compile using C++17:

g++ -std=c++17 -Wall -Wextra -g program.cpp -o program

Compile using C++20:

g++ -std=c++20 -Wall -Wextra program.cpp -o program

3. Tokens and Keywords

Tokens are the smallest individual elements of a C++ program.

Types of Tokens

TokenExample
Keywordsint, class, return
Identifierstotal, student
Constants10, 3.14
String literals"Hello"
Operators+, -, *
Punctuators;, {}, ()

Identifier Rules

  1. Must begin with a letter or underscore.
  2. Cannot begin with a digit.
  3. Cannot contain spaces.
  4. Cannot use reserved keywords.
  5. C++ is case-sensitive.
int total; int _number; int marks1; // Invalid: // int 1marks; // int my marks; // int class;

Common C++ Keywords

CategoryKeywords
Data typesint, char, float, double, void, bool
Decision-makingif, else, switch, case, default
Loopsfor, while, do
Jump statementsbreak, continue, goto, return
OOPclass, public, private, protected, this
Inheritancevirtual, override, final
Memorynew, delete
Templatestemplate, typename
Exception handlingtry, catch, throw
Otherconst, static, extern, sizeof, namespace, using, auto, nullptr

4. Data Types

Data types specify the kind of data a variable can store.

4.1 Fundamental Data Types

Data TypeTypical SizeExample
bool1 bytetrue
char1 byte'A'
int4 bytes100
float4 bytes10.5f
double8 bytes25.567
long doublePlatform-dependent12.345L
voidNo valuevoid

Note: Sizes are implementation-dependent except for sizeof(char), which is always 1 byte.

4.2 Type Modifiers

ModifierDescription
signedPositive and negative values
unsignedNon-negative values
shortShort integer type
longExtended integer type
long longAt least 64-bit integer range
short int a = 10; long int b = 100000; long long int c = 123456789; unsigned int d = 50; signed int e = -20;

4.3 Derived Data Types

4.4 User-Defined Data Types

5. Variables and Constants

5.1 Variable Declaration

int age; float salary; char grade; string name;

5.2 Variable Initialization

int age = 22; float price = 99.50f; char grade = 'A'; string name = "Uday";

5.3 Multiple Variable Declaration

int a = 10, b = 20, c = 30;

5.4 Constants Using const

const float PI = 3.14159f;

5.5 Constants Using constexpr

constexpr int MAX = 100;

constexpr allows expressions to be evaluated at compile time when their requirements are satisfied.

5.6 Auto Keyword

Automatically deduces the variable's type.

auto a = 10; auto b = 10.5; auto name = "Uday";

6. Input and Output

Header file: <iostream>

6.1 cout

Displays output.

cout << "Hello World";

6.2 cin

Accepts input.

int age; cin >> age;

6.3 getline()

Reads an entire line, including spaces.

string name; getline(cin, name); cout << name;

6.4 cerr

Displays error messages.

cerr << "Error occurred!";

6.5 clog

Displays logging information.

clog << "Program started";

6.6 Input and Output Operators

OperatorPurpose
<<Insertion operator
>>Extraction operator

Example:

#include <iostream> using namespace std; int main() { int a, b; cout << "Enter two numbers: "; cin >> a >> b; cout << "Sum = " << a + b; return 0; }

7. Escape Sequences

Escape SequenceMeaning
\nNew line
\tHorizontal tab
\bBackspace
\rCarriage return
\aAlert/bell
\\Backslash
\'Single quotation mark
\"Double quotation mark
\0Null character
\vVertical tab
\fForm feed

Example:

cout << "Hello\nWorld"; cout << "Name:\tUday"; cout << "\"C++ Programming\"";

8. Operators

Operators perform operations on variables and values.

8.1 Arithmetic Operators

OperatorOperationExample
+Additiona + b
-Subtractiona - b
*Multiplicationa * b
/Divisiona / b
%Modulusa % b
int a = 10, b = 3; cout << a + b; // 13 cout << a / b; // 3 cout << a % b; // 1

8.2 Relational Operators

OperatorMeaning
==Equal to
!=Not equal to
>Greater than
<Less than
>=Greater than or equal
<=Less than or equal

8.3 Logical Operators

OperatorMeaning
&&Logical AND
`
!Logical NOT
int age = 20; if (age >= 18 && age <= 60) { cout << "Eligible"; }

8.4 Assignment Operators

OperatorExampleEquivalent
=a = 5Assign
+=a += 5a = a + 5
-=a -= 5a = a - 5
*=a *= 5a = a * 5
/=a /= 5a = a / 5
%=a %= 5a = a % 5
&=a &= 5Bitwise AND assignment
`=``a
^=a ^= 5Bitwise XOR assignment
<<=a <<= 1Left shift assignment
>>=a >>= 1Right shift assignment

8.5 Increment and Decrement

OperatorMeaning
++aPre-increment
a++Post-increment
--aPre-decrement
a--Post-decrement
int a = 5; cout << ++a; // 6 int b = 5; cout << b++; // 5 // b becomes 6

8.6 Bitwise Operators

OperatorOperation
&Bitwise AND
``
^Bitwise XOR
~Bitwise NOT
<<Left shift
>>Right shift
int a = 5; // 0101 int b = 3; // 0011 cout << (a & b); // 1 cout << (a | b); // 7 cout << (a ^ b); // 6 cout << (a << 1); // 10 cout << (a >> 1); // 2

8.7 Conditional (Ternary) Operator

int a = 10, b = 20; int max = (a > b) ? a : b; cout << max;

8.8 Other Operators

OperatorPurpose
sizeofReturns size in bytes
&Address-of
*Pointer dereference
.Member access
->Pointer member access
::Scope resolution
[]Array subscript
()Function call
newDynamic allocation
deleteReleases dynamically allocated memory

9. Operator Precedence

PriorityOperatorsAssociativity
1::Left to right
2() [] . -> x++ x--Left to right
3++x --x ! ~ sizeof * & new deleteRight to left
4.* ->*Left to right
5* / %Left to right
6+ -Left to right
7<< >>Left to right
8< <= > >=Left to right
9== !=Left to right
10&Left to right
11^Left to right
12``
13&&Left to right
14`
15?:Right to left
16Assignment operatorsRight to left
17,Left to right

10. Type Conversion

Type conversion changes a value from one data type to another.

10.1 Implicit Type Conversion

Automatically performed by the compiler.

int a = 10; double b = 5.5; double result = a + b;

10.2 C-Style Casting

int a = 10, b = 3; double result = (double)a / b;

10.3 static_cast

int a = 10; double result = static_cast<double>(a);

10.4 dynamic_cast

Used for checked conversions in polymorphic class hierarchies.

Base* base = new Derived; Derived* derived = dynamic_cast<Derived*>(base); delete base;

10.5 const_cast

Adds or removes const/volatile qualification.

const int a = 10; const int* p = &a;

Use care: modifying an object originally declared const through a cast is undefined behavior.

10.6 reinterpret_cast

Performs low-level reinterpretation of pointer or integer values where permitted.

int a = 10; int* ptr = &a; uintptr_t address = reinterpret_cast<uintptr_t>(ptr);

Requires <cstdint> for uintptr_t where supported.

11. Decision-Making Statements

11.1 if Statement

if (condition) { // Statements }

11.2 if-else Statement

if (condition) { // True block } else { // False block }

11.3 else-if Ladder

int marks = 75; if (marks >= 90) { cout << "Grade A"; } else if (marks >= 75) { cout << "Grade B"; } else if (marks >= 50) { cout << "Grade C"; } else { cout << "Fail"; }

11.4 Nested if

if (age >= 18) { if (age <= 60) { cout << "Eligible"; } }

11.5 switch Statement

int choice = 2; switch (choice) { case 1: cout << "One"; break; case 2: cout << "Two"; break; case 3: cout << "Three"; break; default: cout << "Invalid choice"; }

11.6 Modern switch Initializer (C++17)

switch (int value = 2; value) { case 1: cout << "One"; break; case 2: cout << "Two"; break; }

12. Looping Statements

12.1 for Loop

for (int i = 1; i <= 5; i++) { cout << i << endl; }

12.2 while Loop

int i = 1; while (i <= 5) { cout << i << endl; i++; }

12.3 do-while Loop

int i = 1; do { cout << i << endl; i++; } while (i <= 5);

12.4 Range-Based for Loop

int arr[] = {10, 20, 30, 40}; for (int x : arr) { cout << x << endl; }

12.5 Nested Loop

for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 3; j++) { cout << "* "; } cout << endl; }

12.6 Loop Control Statements

StatementPurpose
breakTerminates nearest loop
continueSkips current iteration
gotoTransfers control to a labeled statement
returnExits a function

13. Arrays

An array stores multiple values of the same data type in contiguous memory.

13.1 One-Dimensional Array

int numbers[5] = {10, 20, 30, 40, 50}; cout << numbers[0];

13.2 Array Input and Output

#include <iostream> using namespace std; int main() { int arr[5]; for (int i = 0; i < 5; i++) { cin >> arr[i]; } for (int i = 0; i < 5; i++) { cout << arr[i] << " "; } return 0; }

13.3 Two-Dimensional Array

int matrix[2][2] = { {1, 2}, {3, 4} }; cout << matrix[0][1];

13.4 Matrix Traversal

for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { cout << matrix[i][j] << " "; } cout << endl; }

13.5 Three-Dimensional Array

int arr[2][3][4];

13.6 Important Array Operations

13.7 STL Array

Header file: <array>

#include <array> array<int, 5> arr = {10, 20, 30, 40, 50}; cout << arr.size(); cout << arr.at(0);

14. Strings

C++ provides two common ways to work with strings.

14.1 C-Style Strings

char name[20] = "Uday"; cout << name;

14.2 C++ String

Header file: <string>

#include <iostream> #include <string> using namespace std; int main() { string name = "Uday"; cout << name; return 0; }

14.3 String Input

string name; cin >> name;

Reads one word.

For complete lines:

string name; getline(cin, name);

14.4 Common String Functions

FunctionPurpose
length()Returns string length
size()Returns string size
empty()Checks whether string is empty
append()Adds text
clear()Removes all characters
substr()Extracts substring
find()Finds a substring or character
replace()Replaces part of a string
erase()Removes characters
insert()Inserts characters
compare()Compares strings
at()Accesses character with bounds checking
push_back()Adds one character
pop_back()Removes last character

Example:

string str = "Hello"; cout << str.length(); str.append(" World"); cout << str; cout << str.substr(0, 5);

15. Functions

A function is a reusable block of code that performs a specific task.

15.1 Function Declaration

int add(int, int);

15.2 Function Definition

int add(int a, int b) { return a + b; }

15.3 Function Calling

int result = add(10, 20);

Complete Example

#include <iostream> using namespace std; int add(int, int); int main() { int result = add(10, 20); cout << "Sum = " << result; return 0; } int add(int a, int b) { return a + b; }

15.4 Types of Functions

TypeArgumentsReturn Value
1NoNo
2YesNo
3NoYes
4YesYes

15.5 Default Arguments

int add(int a, int b = 10) { return a + b; } cout << add(5); // 15 cout << add(5, 5); // 10

15.6 Inline Functions

inline int square(int x) { return x * x; }

15.7 Function Prototypes

A function prototype declares the function before its use.

int multiply(int, int);

15.8 Pass by Value

void change(int x) { x = 100; }

The original variable is not changed.

15.9 Pass by Reference

void change(int &x) { x = 100; }

The original variable is modified.

15.10 Pass by Pointer

void change(int *x) { if (x != nullptr) { *x = 100; } }

16. Recursion

Recursion occurs when a function calls itself.

Factorial Using Recursion

int factorial(int n) { if (n <= 1) return 1; return n * factorial(n - 1); }

Fibonacci Using Recursion

int fibonacci(int n) { if (n <= 1) return n; return fibonacci(n - 1) + fibonacci(n - 2); }

Important: Always define a base condition to prevent infinite recursion.

17. Pointers

A pointer stores the memory address of another object.

17.1 Pointer Declaration

int *ptr;

17.2 Pointer Initialization

int a = 10; int *ptr = &a;

17.3 Dereferencing

cout << *ptr;

17.4 Pointer Example

#include <iostream> using namespace std; int main() { int a = 10; int *ptr = &a; cout << "Value: " << a << endl; cout << "Address: " << ptr << endl; cout << "Dereferenced value: " << *ptr << endl; return 0; }

17.5 NULL and nullptr

int *p1 = nullptr;

nullptr is the modern C++ null pointer literal.

17.6 Pointer to Pointer

int a = 10; int *p = &a; int **pp = &p; cout << **pp;

17.7 Pointer Arithmetic

int arr[] = {10, 20, 30}; int *p = arr; cout << *p << endl; cout << *(p + 1) << endl; cout << *(p + 2) << endl;

17.8 Array of Pointers

int a = 10, b = 20, c = 30; int *arr[] = {&a, &b, &c}; cout << *arr[0];

17.9 Function Pointer

int add(int a, int b) { return a + b; } int (*ptr)(int, int) = add; cout << ptr(10, 20);

18. References

A reference is another name for an existing variable.

18.1 Reference Declaration

int a = 10; int &ref = a;

18.2 Modifying Through Reference

int a = 10; int &ref = a; ref = 50; cout << a; // 50

18.3 Reference as Function Argument

void swap(int &a, int &b) { int temp = a; a = b; b = temp; }

18.4 Constant Reference

const string &name = someString;

Prevents modification through that reference.

Pointer vs Reference

PointerReference
Stores an addressActs as an alias
Can be nullMust be initialized
Can be reassignedCannot be reseated
Uses * for dereferencingUsed directly
Supports pointer arithmeticNo pointer arithmetic

19. Dynamic Memory Allocation

C++ provides new and delete for dynamic memory management.

19.1 new Operator

int *ptr = new int; *ptr = 100; cout << *ptr;

19.2 delete Operator

delete ptr; ptr = nullptr;

19.3 Dynamic Array

int *arr = new int[5]; for (int i = 0; i < 5; i++) { arr[i] = i + 1; } delete[] arr; arr = nullptr;

19.4 Dynamic Object

class Student { public: int roll; }; Student *s = new Student; s->roll = 101; delete s;

19.5 Smart Pointers

Header file: <memory>

#include <memory> auto ptr = make_unique<int>(100); cout << *ptr;

Common smart pointers:

Smart PointerPurpose
unique_ptrExclusive ownership
shared_ptrShared ownership
weak_ptrNon-owning reference to shared object

Prefer smart pointers and standard containers over manual memory management when possible.

20. Object-Oriented Programming

Object-Oriented Programming (OOP) organizes programs around classes and objects.

Four Main Pillars of OOP

  1. Encapsulation
  2. Abstraction
  3. Inheritance
  4. Polymorphism

Benefits of OOP

21. Classes and Objects

21.1 Class

A class is a user-defined blueprint for creating objects.

class Student { public: int roll; string name; void display() { cout << roll << " " << name; } };

21.2 Object

An object is an instance of a class.

Student s1; s1.roll = 101; s1.name = "Uday"; s1.display();

21.3 Access Specifiers

Access SpecifierDescription
publicAccessible from anywhere permitted by the object
privateAccessible within the class and its friends
protectedAccessible within the class, friends, and derived classes

21.4 Complete Class Example

#include <iostream> using namespace std; class Student { private: int roll; public: void setRoll(int r) { roll = r; } void display() { cout << "Roll: " << roll; } }; int main() { Student s1; s1.setRoll(101); s1.display(); return 0; }

22. Constructors and Destructors

22.1 Constructor

A constructor is a special member function automatically called when an object is initialized.

class Student { public: Student() { cout << "Constructor called"; } };

22.2 Default Constructor

class Student { public: Student() { cout << "Default Constructor"; } };

22.3 Parameterized Constructor

class Student { public: int roll; Student(int r) { roll = r; } };

22.4 Copy Constructor

class Student { public: int roll; Student(const Student &s) { roll = s.roll; } };

22.5 Constructor Overloading

class Student { public: Student() { cout << "Default"; } Student(int x) { cout << x; } };

22.6 Destructor

A destructor is called when an object is destroyed.

class Student { public: ~Student() { cout << "Destructor called"; } };

Constructor vs Destructor

ConstructorDestructor
Initializes an objectCleans up an object
Same name as classSame name with ~
Can be overloadedCannot be overloaded
May have parametersHas no parameters
Called during initializationCalled during destruction

23. Encapsulation

Encapsulation means combining data and functions within a class while controlling access to internal data.

Example:

class BankAccount { private: double balance = 0; public: void deposit(double amount) { if (amount > 0) balance += amount; } double getBalance() { return balance; } };

24. Abstraction

Abstraction hides implementation details and exposes essential functionality.

Example:

class ATM { public: void withdraw() { cout << "Withdrawal process"; } };

Users interact with the public interface without needing to understand its internal implementation.

Abstract Class

An abstract class has at least one pure virtual function.

class Shape { public: virtual void draw() = 0; };

An abstract class cannot be instantiated directly.

25. Inheritance

Inheritance allows one class to acquire the properties and behaviors of another class.

25.1 Single Inheritance

class Animal { public: void eat() { cout << "Eating"; } }; class Dog : public Animal { public: void bark() { cout << "Barking"; } };

25.2 Multilevel Inheritance

class A { public: void showA() {} }; class B : public A { public: void showB() {} }; class C : public B { public: void showC() {} };

25.3 Multiple Inheritance

class A { }; class B { }; class C : public A, public B { };

25.4 Hierarchical Inheritance

class Animal { }; class Dog : public Animal { }; class Cat : public Animal { };

25.5 Hybrid Inheritance

A combination of two or more inheritance types.

Types of Inheritance

TypeDescription
SingleOne base and one derived class
MultipleMultiple base classes
MultilevelA class derived from another derived class
HierarchicalMultiple derived classes from one base class
HybridCombination of inheritance types

Inheritance Access Modes

Base MemberPublic InheritanceProtected InheritancePrivate Inheritance
PublicPublicProtectedPrivate
ProtectedProtectedProtectedPrivate
PrivateNot directly accessibleNot directly accessibleNot directly accessible

26. Polymorphism

Polymorphism means one interface can represent multiple forms of behavior.

Types of Polymorphism

  1. Compile-time polymorphism
  2. Runtime polymorphism

Compile-Time Polymorphism

Runtime Polymorphism

27. Function Overloading

Multiple functions can have the same name but different parameter lists.

#include <iostream> using namespace std; int add(int a, int b) { return a + b; } double add(double a, double b) { return a + b; } int main() { cout << add(10, 20) << endl; cout << add(2.5, 3.5); return 0; }

Note: Functions cannot be overloaded only by changing their return type.

28. Operator Overloading

Operator overloading allows operators to work with user-defined types.

Example:

#include <iostream> using namespace std; class Number { public: int value; Number(int v) : value(v) {} Number operator+(const Number &n) { return Number(value + n.value); } }; int main() { Number a(10), b(20); Number c = a + b; cout << c.value; return 0; }

Common overloadable operators:

Some operators, including ::, ., .*, ?:, and sizeof, cannot be overloaded.

29. Virtual Functions

Virtual functions support runtime polymorphism.

#include <iostream> using namespace std; class Animal { public: virtual void sound() { cout << "Animal sound"; } virtual ~Animal() = default; }; class Dog : public Animal { public: void sound() override { cout << "Dog barks"; } }; int main() { Dog d; Animal *ptr = &d; ptr->sound(); return 0; }

Output:

Dog barks

Important Concepts

ConceptDescription
virtualEnables dynamic dispatch
overrideVerifies that a function overrides a base virtual function
finalPrevents further overriding or inheritance
Pure virtual functionDeclared with = 0
Abstract classClass with at least one pure virtual function

30. Friend Functions

A friend function can access private and protected members of a class.

#include <iostream> using namespace std; class Box { private: int value = 100; public: friend void display(Box); }; void display(Box b) { cout << b.value; }

Friend functions are not member functions of the class.

31. Static Members

Static members belong to the class rather than individual objects.

31.1 Static Data Member

class Student { public: static int count; }; int Student::count = 0;

31.2 Static Member Function

class Student { public: static int count; static void display() { cout << count; } }; int Student::count = 10;

Call using:

Student::display();

32. Templates

Templates support generic programming by allowing functions and classes to work with different data types.

32.1 Function Template

template <typename T> T add(T a, T b) { return a + b; } int main() { cout << add(10, 20) << endl; cout << add(2.5, 3.5); }

32.2 Class Template

template <typename T> class Box { public: T value; Box(T v) { value = v; } };

Usage:

Box<int> b1(100); Box<string> b2("Hello");

32.3 Multiple Template Parameters

template <typename T, typename U> class Pair { public: T first; U second; };

32.4 Template Specialization

template <typename T> class Data { }; template <> class Data<int> { };

33. Exception Handling

Exception handling manages runtime errors using try, catch, and throw.

33.1 try and catch

try { int age = -1; if (age < 0) throw age; } catch (int e) { cout << "Invalid age"; }

33.2 Multiple catch Blocks

try { throw 10; } catch (int e) { cout << "Integer exception"; } catch (double e) { cout << "Double exception"; } catch (...) { cout << "Unknown exception"; }

33.3 Standard Exceptions

Header file: <stdexcept>

ExceptionDescription
exceptionBase exception class
runtime_errorRuntime error
logic_errorLogic error
invalid_argumentInvalid argument
out_of_rangeOut-of-range access
length_errorLength-related error
bad_allocMemory allocation failure

Example:

#include <iostream> #include <stdexcept> using namespace std; int main() { try { throw runtime_error("Something went wrong"); } catch (const exception &e) { cout << e.what(); } return 0; }

34. File Handling

C++ provides file handling through the <fstream> library.

34.1 File Stream Classes

ClassPurpose
ifstreamReads files
ofstreamWrites files
fstreamReads and writes files

34.2 Writing to a File

#include <iostream> #include <fstream> using namespace std; int main() { ofstream file("data.txt"); if (!file) return 1; file << "Hello C++ Programming"; file.close(); return 0; }

34.3 Reading from a File

#include <iostream> #include <fstream> #include <string> using namespace std; int main() { ifstream file("data.txt"); if (!file) return 1; string line; while (getline(file, line)) { cout << line << endl; } file.close(); return 0; }

34.4 File Opening Modes

ModeDescription
ios::inRead
ios::outWrite
ios::appAppend
ios::ateOpen and position at end
ios::truncTruncate existing contents
ios::binaryBinary mode

34.5 Important File Functions

FunctionPurpose
open()Opens a file
close()Closes a file
is_open()Checks whether a file is open
getline()Reads a line
get()Reads a character
put()Writes a character
read()Reads binary data
write()Writes binary data
seekg()Changes input position
seekp()Changes output position
tellg()Returns input position
tellp()Returns output position
eof()Checks end-of-file state

35. Standard Template Library (STL)

STL is a collection of generic classes and functions for common programming tasks.

Main Components

  1. Containers
  2. Iterators
  3. Algorithms
  4. Function objects

35.1 Vector

Header: <vector>

A dynamic array.

#include <vector> vector<int> v = {10, 20, 30}; v.push_back(40); v.pop_back(); cout << v.size(); cout << v[0];

Common functions:

FunctionPurpose
push_back()Adds an element
pop_back()Removes last element
size()Returns number of elements
empty()Checks whether empty
clear()Removes all elements
at()Accesses with bounds checking
front()First element
back()Last element
begin()Iterator to first element
end()Iterator past last element
insert()Inserts elements
erase()Removes elements

35.2 Array

Header: <array>

#include <array> array<int, 3> arr = {10, 20, 30}; cout << arr.size();

35.3 List

Header: <list>

Doubly linked list.

#include <list> list<int> l = {10, 20, 30}; l.push_front(5); l.push_back(40); l.pop_front();

35.4 Forward List

Header: <forward_list>

Singly linked list.

#include <forward_list> forward_list<int> l = {10, 20, 30}; l.push_front(5);

35.5 Deque

Header: <deque>

Double-ended queue.

#include <deque> deque<int> d = {10, 20, 30}; d.push_front(5); d.push_back(40);

35.6 Stack

Header: <stack>

Follows LIFO (Last In, First Out).

#include <stack> stack<int> s; s.push(10); s.push(20); cout << s.top(); s.pop();

35.7 Queue

Header: <queue>

Follows FIFO (First In, First Out).

#include <queue> queue<int> q; q.push(10); q.push(20); cout << q.front(); q.pop();

35.8 Priority Queue

Header: <queue>

By default, a max-heap.

#include <queue> priority_queue<int> pq; pq.push(10); pq.push(30); pq.push(20); cout << pq.top(); // 30

Min-heap:

priority_queue<int, vector<int>, greater<int>> pq;

35.9 Set

Header: <set>

Stores unique sorted elements.

#include <set> set<int> s = {30, 10, 20, 10}; s.insert(40); s.erase(10);

35.10 Multiset

Allows duplicate sorted elements.

#include <set> multiset<int> ms = {10, 20, 10};

35.11 Map

Header: <map>

Stores unique sorted key-value pairs.

#include <map> map<int, string> m; m[1] = "Uday"; m[2] = "Rahul"; cout << m[1];

35.12 Multimap

Allows duplicate keys.

#include <map> multimap<int, string> m; m.insert({1, "Uday"}); m.insert({1, "Rahul"});

35.13 Unordered Set

Header: <unordered_set>

Stores unique elements without sorted order.

#include <unordered_set> unordered_set<int> s = {10, 20, 30}; s.insert(40);

35.14 Unordered Map

Header: <unordered_map>

Stores key-value pairs using hashing.

#include <unordered_map> unordered_map<string, int> marks; marks["Uday"] = 90; marks["Rahul"] = 85;

STL Container Comparison

ContainerData StructureMain Feature
vectorDynamic arrayFast random access
arrayFixed-size arrayFixed capacity
listDoubly linked listEfficient insertion/removal at known positions
forward_listSingly linked listForward-only traversal
dequeDouble-ended arrayEfficient operations at both ends
stackAdapterLIFO
queueAdapterFIFO
priority_queueHeap adapterHighest priority first by default
setBalanced treeUnique sorted values
multisetBalanced treeDuplicate sorted values
mapBalanced treeUnique sorted keys
multimapBalanced treeDuplicate sorted keys
unordered_setHash tableUnique unordered values
unordered_mapHash tableUnique unordered keys

36. Iterators

Iterators provide a way to access elements of STL containers.

Types of Iterators

TypeDescription
InputReads elements
OutputWrites elements
ForwardMoves forward
BidirectionalMoves forward and backward
Random accessSupports direct movement
ContiguousProvides contiguous storage traversal

Iterator Example

#include <iostream> #include <vector> using namespace std; int main() { vector<int> v = {10, 20, 30}; for (auto it = v.begin(); it != v.end(); ++it) { cout << *it << " "; } return 0; }

Range-Based Loop

for (int x : v) { cout << x << " "; }

37. Lambda Expressions

Lambda expressions create anonymous functions.

Syntax:

[capture](parameters) -> return_type { // Statements };

Example:

auto add = [](int a, int b) { return a + b; }; cout << add(10, 20);

Lambda with Capture

int x = 10; auto show = [x]() { cout << x; }; show();

Lambda Capture Types

CaptureMeaning
[]No capture
[=]Capture used variables by value
[&]Capture used variables by reference
[x]Capture x by value
[&x]Capture x by reference
[this]Capture current object pointer

38. Namespaces

Namespaces organize code and prevent naming conflicts.

Namespace Declaration

namespace MySpace { int value = 100; }

Accessing Namespace Members

cout << MySpace::value;

using Declaration

using std::cout; using std::endl;

using Namespace

using namespace std;

Avoid unnecessarily importing entire namespaces in header files.

39. Preprocessor Directives

Preprocessor directives are processed before compilation.

39.1 #include

#include <iostream> #include "myheader.h"

39.2 #define

#define PI 3.14159 #define SQUARE(x) ((x) * (x))

39.3 #undef

#undef PI

39.4 Conditional Compilation

#ifdef DEBUG cout << "Debug mode"; #endif

Other directives:

#if #elif #else #endif #ifndef

39.5 Header Guards

#ifndef MYHEADER_H #define MYHEADER_H void display(); #endif

39.6 pragma once

#pragma once

Commonly used to prevent repeated inclusion, although it is not part of the C++ standard.

40. Type Modifiers and Storage

40.1 Type Modifiers

ModifierPurpose
signedSigned numeric values
unsignedNon-negative integer values
shortShort integer type
longExtended integer type

40.2 Storage Class and Related Keywords

KeywordPurpose
autoAutomatic type deduction in modern C++
staticStatic storage duration or class-level member
externExternal linkage declaration
registerDeprecated storage-class specifier
thread_localThread-local storage duration
mutableAllows modification of selected members in const objects
constPrevents modification through an identifier
volatileIndicates potentially externally changing data

41. Modern C++ Features

41.1 auto

auto x = 10; auto name = string("Uday");

41.2 nullptr

int *ptr = nullptr;

41.3 Range-Based for

for (int x : arr) { cout << x; }

41.4 Smart Pointers

auto ptr = make_unique<int>(100);

41.5 Move Semantics

#include <utility> string a = "Hello"; string b = move(a);

std::move enables move operations; it does not itself move data.

41.6 Structured Bindings (C++17)

pair<int, string> p = {1, "Uday"}; auto [id, name] = p;

41.7 Optional (C++17)

#include <optional> optional<int> value = 10;

41.8 Null Coalescing Alternative

C++ does not have a built-in ?? operator. Use conditional expressions or optional::value_or().

optional<int> value; int result = value.value_or(0);

41.9 constexpr

constexpr int square(int x) { return x * x; }

41.10 Concepts (C++20)

#include <concepts> template <typename T> requires integral<T> T add(T a, T b) { return a + b; }

41.11 Ranges (C++20)

#include <ranges> #include <vector> vector<int> v = {1, 2, 3, 4, 5}; for (int x : v | views::filter([](int n) { return n % 2 == 0; })) { cout << x << " "; }

42. Important Standard Libraries

HeaderPurpose
<iostream>Input and output
<iomanip>Output formatting
<string>String handling
<vector>Dynamic arrays
<array>Fixed-size arrays
<list>Doubly linked list
<forward_list>Singly linked list
<deque>Double-ended queue
<stack>Stack
<queue>Queue and priority queue
<set>Set and multiset
<map>Map and multimap
<unordered_set>Hash-based set
<unordered_map>Hash-based map
<algorithm>Sorting and algorithms
<numeric>Numeric algorithms
<iterator>Iterator utilities
<functional>Function objects
<memory>Smart pointers
<fstream>File handling
<sstream>String streams
<cmath>Mathematical functions
<cstdlib>General utilities
<cstring>C-style string functions
<cctype>Character handling
<ctime>Date and time
<random>Random number generation
<stdexcept>Standard exceptions
<exception>Exception support
<utility>Pair, move, swap
<optional>Optional values
<variant>Type-safe alternatives
<tuple>Multiple-value objects
<thread>Thread support
<mutex>Synchronization
<filesystem>Filesystem operations

43. Common Programming Problems

ProblemBasic Logic
Even or oddn % 2 == 0
Positive or negativeCompare with zero
Largest of two numbersCompare values
Largest of three numbersMultiple comparisons
Swap two numbersTemporary variable
FactorialRepeated multiplication
Prime numberCheck divisors up to square root
Fibonacci seriesAdd previous two terms
Reverse a numberExtract digits using % 10
Palindrome numberCompare with reversed number
Armstrong numberSum digits raised to number of digits
Sum of digitsRepeated % 10
Count digitsRepeated division by 10
GCDEuclidean algorithm
LCMa / gcd(a,b) * b for nonzero inputs

43.1 Even or Odd

if (n % 2 == 0) cout << "Even"; else cout << "Odd";

43.2 Factorial

int fact = 1; for (int i = 1; i <= n; i++) { fact *= i; }

43.3 Prime Number

bool isPrime = true; if (n <= 1) { isPrime = false; } else { for (int i = 2; i <= n / i; i++) { if (n % i == 0) { isPrime = false; break; } } } cout << (isPrime ? "Prime" : "Not Prime");

44. Pattern Programs

44.1 Square Pattern

for (int i = 1; i <= 5; i++) { for (int j = 1; j <= 5; j++) { cout << "* "; } cout << endl; }

Output:

* * * * * * * * * * * * * * * * * * * * * * * * *

44.2 Right Triangle

for (int i = 1; i <= 5; i++) { for (int j = 1; j <= i; j++) { cout << "* "; } cout << endl; }

44.3 Inverted Triangle

for (int i = 5; i >= 1; i--) { for (int j = 1; j <= i; j++) { cout << "* "; } cout << endl; }

44.4 Number Triangle

for (int i = 1; i <= 5; i++) { for (int j = 1; j <= i; j++) { cout << j << " "; } cout << endl; }

45. Time and Space Complexity

Complexity describes the efficiency of an algorithm.

Common Time Complexities

ComplexityNameExample
O(1)ConstantArray element access
O(log n)LogarithmicBinary search
O(n)LinearArray traversal
O(n log n)LinearithmicMerge sort
O(n²)QuadraticBubble sort
O(n³)CubicBasic triple nested loops
O(2ⁿ)ExponentialNaive recursive Fibonacci
O(n!)FactorialBrute-force permutations

Common Sorting Algorithms

AlgorithmAverage TimeWorst Time
Bubble SortO(n²)O(n²)
Selection SortO(n²)O(n²)
Insertion SortO(n²)O(n²)
Merge SortO(n log n)O(n log n)
Quick SortO(n log n)O(n²)
Heap SortO(n log n)O(n log n)

Searching Algorithms

AlgorithmAverage/Worst Time
Linear SearchO(n)
Binary SearchO(log n)

Binary search requires sorted data.

46. Common Errors

ErrorMeaning
Syntax errorIncorrect syntax
Runtime errorError during execution
Logical errorIncorrect program output
Linker errorProblem linking components
Compilation errorCompiler cannot compile source code
Segmentation faultInvalid memory access

Common Mistakes

// Missing semicolon int a = 10 // Assignment instead of comparison if (a = 10) // Uninitialized pointer int *ptr; *ptr = 10; // Array out of bounds int arr[5]; arr[5] = 10;

Correct Versions

int a = 10; if (a == 10) { cout << "Equal"; } int *ptr = nullptr; int arr[5]; arr[4] = 10;

47. Quick Syntax Reference

TaskSyntax
Print outputcout << "Hello";
Read inputcin >> a;
Read full linegetline(cin, str);
Declare integerint a;
Declare floatfloat a;
Declare stringstring name;
Declare arrayint arr[10];
Declare vectorvector<int> v;
Declare pointerint *ptr;
Declare referenceint &ref = a;
Declare functionint add(int a, int b);
Declare classclass Student {};
Create objectStudent s1;
Allocate memorynew int;
Release memorydelete ptr;
Open fileifstream file("data.txt");
Return valuereturn value;
Include library#include <iostream>
Namespace accessstd::cout

48. C++ Best Practices

  1. Use meaningful variable and function names.
  2. Initialize variables before using them.
  3. Use const wherever appropriate.
  4. Prefer nullptr over NULL.
  5. Prefer std::string over C-style strings for normal text handling.
  6. Prefer std::vector over raw dynamic arrays.
  7. Prefer smart pointers over manual memory management.
  8. Use references when appropriate to avoid unnecessary copies.
  9. Use override when overriding virtual functions.
  10. Keep classes and functions small and focused.
  11. Use exception handling for exceptional conditions.
  12. Avoid unnecessary global variables.
  13. Compile with warnings enabled.
  14. Follow proper indentation and formatting.
  15. Use standard library algorithms whenever suitable.
  16. Avoid memory leaks and dangling pointers.
  17. Use RAII for resource management.
  18. Write reusable and modular code.

Conclusion

C++ is an important programming language for software development, competitive programming, game development, embedded systems, and system programming.

To master C++:

  1. Learn fundamental programming concepts.
  2. Understand operators and control structures.
  3. Practice arrays, strings, and functions.
  4. Master pointers and references.
  5. Understand object-oriented programming.
  6. Practice inheritance and polymorphism.
  7. Learn templates and exception handling.
  8. Master STL containers and algorithms.
  9. Build practical projects.

Learn. Build. Grow. — Ugenz Academy