Learn CPP with Real Code Examples
Updated Nov 27, 2025
Code Sample Descriptions
C++ Class Example
#include <iostream>
#include <vector>
#include <string>
class Person {
private:
std::string name;
int age;
public:
Person(const std::string& name, int age)
: name(name), age(age) {}
void introduce() const {
std::cout << "Hi, I'm " << name << " and I'm " << age << " years old." << std::endl;
}
int getAge() const { return age; }
};
int main() {
std::vector<Person> people = { Person("Alice", 25), Person("Bob", 30) };
for (const auto& person : people) {
person.introduce();
}
return 0;
}
Demonstrates key C++ features including classes, vectors, and modern C++ syntax.
C++ Inheritance Example
#include <iostream>
class Animal {
public:
void speak() { std::cout << "Animal sound" << std::endl; }
};
class Dog : public Animal {
public:
void speak() { std::cout << "Woof!" << std::endl; }
};
int main() {
Dog dog;
dog.speak();
return 0;
}
Shows basic inheritance with a base class and a derived class.
C++ Lambda Example
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
std::for_each(numbers.begin(), numbers.end(), [](int n){ std::cout << n*n << ' '; });
return 0;
}
Demonstrates using a lambda function to transform a vector.
C++ Smart Pointer Example
#include <iostream>
#include <memory>
class Resource {
public:
Resource() { std::cout << "Resource acquired\n"; }
~Resource() { std::cout << "Resource destroyed\n"; }
};
int main() {
auto res = std::make_unique<Resource>();
return 0;
}
Uses std::unique_ptr to manage dynamic memory safely.
C++ Template Function Example
#include <iostream>
template<typename T>
T maxValue(T a, T b) {
return (a > b) ? a : b;
}
int main() {
std::cout << maxValue(10, 20) << std::endl;
std::cout << maxValue(3.5, 2.1) << std::endl;
return 0;
}
Demonstrates a template function to find the maximum of two values.
C++ Exception Handling
#include <iostream>
#include <stdexcept>
int main() {
try {
throw std::runtime_error("Something went wrong");
} catch (const std::exception& e) {
std::cout << "Caught exception: " << e.what() << std::endl;
}
return 0;
}
Shows basic try-catch exception handling in C++.
C++ STL Map Example
#include <iostream>
#include <map>
#include <string>
int main() {
std::map<std::string, int> ages = { {"Alice", 25}, {"Bob", 30} };
for (const auto& [name, age] : ages) {
std::cout << name << " is " << age << " years old\n";
}
return 0;
}
Demonstrates using std::map to store key-value pairs.
C++ Constexpr Example
#include <iostream>
constexpr int square(int x) { return x*x; }
int main() {
std::cout << square(5) << std::endl;
return 0;
}
Uses constexpr for compile-time computation.
C++ Move Semantics Example
#include <iostream>
#include <vector>
class Buffer {
public:
std::vector<int> data;
Buffer(std::vector<int> d) : data(std::move(d)) {}
};
int main() {
std::vector<int> v = {1,2,3};
Buffer buf(std::move(v));
std::cout << "Buffer size: " << buf.data.size() << std::endl;
return 0;
}
Demonstrates move constructor to optimize resource management.
C++ Enum Class Example
#include <iostream>
enum class Color { Red, Green, Blue };
int main() {
Color c = Color::Green;
if (c == Color::Green) {
std::cout << "Color is green" << std::endl;
}
return 0;
}
Uses enum class for type-safe enumerations.
C++ STL Vector Example
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
for (const auto& n : numbers) {
std::cout << n << ' ';
}
return 0;
}
Demonstrates vector initialization and iteration.
C++ STL Set Example
#include <iostream>
#include <set>
int main() {
std::set<int> s = {1, 2, 3};
s.insert(4);
for (const auto& n : s) {
std::cout << n << ' ';
}
return 0;
}
Demonstrates set insertion and iteration.
C++ Lambda for STL Example
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> v = {1, 2, 3, 4, 5};
std::for_each(v.begin(), v.end(), [](int& n){ n *= 2; });
for (const auto& n : v) {
std::cout << n << ' ';
}
return 0;
}
Uses lambda to modify elements in a vector.
C++ Smart Pointer Shared Example
#include <iostream>
#include <memory>
int main() {
auto sp1 = std::make_shared<int>(10);
auto sp2 = sp1;
std::cout << *sp1 << ',' << *sp2 << std::endl;
return 0;
}
Demonstrates shared_ptr usage.
C++ Move Constructor Example
#include <iostream>
#include <vector>
class Buffer {
public:
std::vector<int> data;
Buffer(std::vector<int> d) : data(std::move(d)) {}
};
int main() {
std::vector<int> v = {1, 2, 3};
Buffer buf(std::move(v));
std::cout << "Buffer size: " << buf.data.size() << std::endl;
return 0;
}
Shows move constructor usage for efficient object transfer.
C++ Vector Sorting Example
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> nums = {5, 2, 9, 1, 3};
std::sort(nums.begin(), nums.end(), [](int a, int b) { return a < b; });
for (int n : nums) std::cout << n << ' ';
return 0;
}
Demonstrates sorting a vector using std::sort with a custom comparator.
C++ Range-Based For Loop
#include <iostream>
#include <vector>
int main() {
std::vector<std::string> words = {"Hello", "World"};
for (const auto& w : words) {
std::cout << w << std::endl;
}
return 0;
}
Shows how range-based for loops provide cleaner iteration.
C++ Struct Initialization
#include <iostream>
#include <string>
struct User {
std::string name;
int age;
};
int main() {
User u{"Alice", 22};
std::cout << u.name << " - " << u.age << std::endl;
return 0;
}
Shows modern uniform initialization for structs.
C++ Optional Example
#include <iostream>
#include <optional>
std::optional<int> divide(int a, int b) {
if (b == 0) return std::nullopt;
return a / b;
}
int main() {
auto result = divide(10, 2);
if (result) std::cout << *result;
return 0;
}
Demonstrates using std::optional to return optional values.
C++ File Reading Example
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ifstream file("test.txt");
std::string line;
while (std::getline(file, line)) {
std::cout << line << std::endl;
}
return 0;
}
Reads lines from a file using std::ifstream.
C++ Set Example
#include <iostream>
#include <set>
int main() {
std::set<int> s = {3, 1, 4, 1, 5};
for (int n : s) std::cout << n << ' ';
return 0;
}
Uses std::set to hold unique sorted values.
C++ Pair Example
#include <iostream>
#include <utility>
int main() {
std::pair<std::string, int> p{"Age", 30};
std::cout << p.first << ": " << p.second;
return 0;
}
Shows how to use std::pair.
C++ Mutex Lock Example
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mtx;
int counter = 0;
void increment() {
std::lock_guard<std::mutex> lock(mtx);
counter++;
}
int main() {
std::thread t1(increment);
std::thread t2(increment);
t1.join();
t2.join();
std::cout << counter;
return 0;
}
Uses std::mutex and std::lock_guard for thread safety.
C++ Thread Example
#include <iostream>
#include <thread>
void run() {
std::cout << "Thread running";
}
int main() {
std::thread t(run);
t.join();
return 0;
}
Creates threads using std::thread.
C++ Vector Push Example
#include <iostream>
#include <vector>
int main() {
std::vector<int> v;
v.push_back(1);
v.push_back(2);
for (int n : v) std::cout << n;
return 0;
}
Shows how to push elements into a vector.
C++ Map Find Example
#include <iostream>
#include <map>
int main() {
std::map<int, std::string> m = {{1, "One"}, {2, "Two"}};
auto it = m.find(2);
if (it != m.end()) std::cout << it->second;
return 0;
}
Demonstrates finding a key in std::map.
C++ Queue Example
#include <iostream>
#include <queue>
int main() {
std::queue<int> q;
q.push(10);
q.push(20);
std::cout << q.front();
return 0;
}
Uses std::queue for FIFO operations.
C++ Stack Example
#include <iostream>
#include <stack>
int main() {
std::stack<int> s;
s.push(5);
s.push(10);
std::cout << s.top();
return 0;
}
Uses std::stack for LIFO operations.
C++ Variant Example
#include <iostream>
#include <variant>
int main() {
std::variant<int, std::string> v = "Hello";
std::cout << std::get<std::string>(v);
return 0;
}
Uses std::variant to hold multiple types.
C++ Tuple Example
#include <iostream>
#include <tuple>
int main() {
auto t = std::make_tuple("Alice", 25, 3.8);
std::cout << std::get<0>(t);
return 0;
}
Uses std::tuple to bundle multiple values.
C++ Unique Lock Example
#include <iostream>
#include <mutex>
#include <thread>
std::mutex mtx;
int value = 0;
void add() {
std::unique_lock<std::mutex> lock(mtx);
value++;
}
int main() {
std::thread t1(add);
std::thread t2(add);
t1.join();
t2.join();
std::cout << value;
return 0;
}
Demonstrates std::unique_lock for flexible mutex handling.
C++ Condition Variable Example
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
std::mutex mtx;
bool ready = false;
std::condition_variable cv;
void worker() {
std::unique_lock<std::mutex> lock(mtx);
cv.wait(lock, []{ return ready; });
std::cout << "Worker running";
}
int main() {
std::thread t(worker);
{
std::lock_guard<std::mutex> lock(mtx);
ready = true;
}
cv.notify_one();
t.join();
return 0;
}
Uses std::condition_variable for thread synchronization.
C++ StringStream Example
#include <iostream>
#include <sstream>
int main() {
std::stringstream ss;
ss << 42;
int num;
ss >> num;
std::cout << num;
return 0;
}
Uses std::stringstream for converting values.
C++ Binary Search Example
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> v = {1, 2, 3, 4, 5};
bool found = std::binary_search(v.begin(), v.end(), 3);
std::cout << (found ? "Found" : "Not found");
return 0;
}
Uses std::binary_search on a sorted vector.
C++ Accumulate Example
#include <iostream>
#include <vector>
#include <numeric>
int main() {
std::vector<int> v = {1, 2, 3, 4};
int sum = std::accumulate(v.begin(), v.end(), 0);
std::cout << sum;
return 0;
}
Uses std::accumulate to sum vector elements.
C++ Find_if Example
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> v = {10, 15, 20, 25};
auto it = std::find_if(v.begin(), v.end(), [](int x) { return x > 18; });
if (it != v.end()) std::cout << *it;
return 0;
}
Demonstrates std::find_if to find matching elements.
C++ Reduce Example
#include <iostream>
#include <vector>
#include <numeric>
int main() {
std::vector<int> v = {1, 2, 3, 4};
int result = std::reduce(v.begin(), v.end());
std::cout << result;
return 0;
}
Uses std::reduce from C++17 for parallel-friendly accumulation.
C++ Algorithm Transform Example
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> v = {1, 2, 3};
std::transform(v.begin(), v.end(), v.begin(), [](int x){ return x * 2; });
for (int n : v) std::cout << n << ' ';
return 0;
}
Uses std::transform to modify elements of a container.
C++ Array Example
#include <iostream>
#include <array>
int main() {
std::array<int, 3> arr = {1, 2, 3};
for (int x : arr) std::cout << x;
return 0;
}
Shows simple usage of std::array.
C++ Deque Example
#include <iostream>
#include <deque>
int main() {
std::deque<int> d;
d.push_front(1);
d.push_back(2);
std::cout << d.front() << d.back();
return 0;
}
Uses std::deque for double-ended operations.
C++ Priority Queue Example
#include <iostream>
#include <queue>
int main() {
std::priority_queue<int> pq;
pq.push(3);
pq.push(1);
pq.push(2);
std::cout << pq.top();
return 0;
}
Uses std::priority_queue as a max-heap.
C++ Bitset Example
#include <iostream>
#include <bitset>
int main() {
std::bitset<8> b("10101010");
std::cout << b;
return 0;
}
Uses std::bitset for efficient bit manipulation.
C++ Chrono Timer Example
#include <iostream>
#include <chrono>
int main() {
auto start = std::chrono::high_resolution_clock::now();
for (int i = 0; i < 1000000; i++);
auto end = std::chrono::high_resolution_clock::now();
std::cout << std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
return 0;
}
Uses std::chrono to measure execution time.
C++ Function Pointer Example
#include <iostream>
int add(int a, int b) { return a + b; }
int main() {
int (*func)(int, int) = add;
std::cout << func(2, 3);
return 0;
}
Shows declaring and using function pointers.
C++ Recursion Example
#include <iostream>
int fact(int n) {
if (n <= 1) return 1;
return n * fact(n - 1);
}
int main() {
std::cout << fact(5);
return 0;
}
Shows a simple recursive factorial function.