Top 30 Trending C++ Coding Examples

To understand these C++ examples, you should know the following:

1. Write a program to reverse a std::string using modern C++ algorithms

Code:

#include <iostream>
#include <string>
#include <algorithm>

int main() {
    std::string str = "Modern C++";
    std::reverse(str.begin(), str.end());
    std::cout << str << std::endl;
    return 0;
}

Output:

++C nredoM

Explanation: std::reverse from <algorithm> reverses the elements in the range [begin, end) in place.

2. Check if a string is a palindrome using std::equal and reverse iterators with C++

Code:

#include <iostream>
#include <string>
#include <algorithm>

bool isPalindrome(const std::string& s) {
    return std::equal(s.begin(), s.begin() + s.size() / 2, s.rbegin());
}

int main() {
    std::string str = "racecar";
    std::cout << (isPalindrome(str) ? "True" : "False") << std::endl;
    return 0;
}

Output:

True

Explanation: std::equal compares the first half of the string forward against the second half traversed in reverse order using rbegin().

3. Use auto and range-based for loops to iterate over a std::vector in C++

Code:

#include <iostream>
#include <vector>

int main() {
    std::vector<int> nums = {10, 20, 30, 40};
    for (const auto& num : nums) {
        std::cout << num << " ";
    }
    std::cout << std::endl;
    return 0;
}

Output:

10 20 30 40

Explanation: Range-based for loop combined with const auto& allows clean, efficient iteration without copying vector elements.

4. Manage dynamic memory safely using std::unique_ptr with C++

Code:

#include <iostream>
#include <memory>

class Resource {
public:
    Resource() { std::cout << "Acquired\n"; }
    ~Resource() { std::cout << "Destroyed\n"; }
    void sayHello() { std::cout << "Hello from Resource\n"; }
};

int main() {
    std::unique_ptr<Resource> ptr = std::make_unique<Resource>();
    ptr->sayHello();
    return 0;
}

Output:

Acquired
Hello from Resource
Destroyed

Explanation: std::unique_ptr automatically frees the dynamically allocated memory when out of scope, preventing memory leaks.

5. Use Lambda functions and std::sort to sort numbers in descending order with C++

Code:

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> nums = {5, 2, 8, 1, 9};
    std::sort(nums.begin(), nums.end(), [](int a, int b) {
        return a > b;
    });
    for (int n : nums) std::cout << n << " ";
    std::cout << std::endl;
    return 0;
}

Output:

9 8 5 2 1

Explanation: A custom lambda comparator [](int a, int b) { return a > b; } is passed to std::sort for custom ordering.

6. Filter and transform collections using C++20 Ranges

Code:

#include <iostream>
#include <vector>
#include <ranges>

int main() {
    std::vector<int> numbers = {1, 2, 3, 4, 5, 6};
    auto even_squares = numbers 
                      | std::views::filter([](int n) { return n % 2 == 0; })
                      | std::views::transform([](int n) { return n * n; });

    for (int n : even_squares) {
        std::cout << n << " ";
    }
    std::cout << std::endl;
    return 0;
}

Output:

4 16 36

Explanation: C++20 ranges pipe operators (|) allow composing view adapters like filter and transform lazily.

7. Store type-safe heterogeneous values using std::variant and std::visit in C++

Code:

#include <iostream>
#include <variant>
#include <string>

int main() {
    std::variant<int, double, std::string> v = "C++ Variant";
    
    std::visit([](const auto& arg) {
        std::cout << "Value: " << arg << std::endl;
    }, v);

    return 0;
}

Output:

Value: C++ Variant

Explanation: std::variant acts as a type-safe union, and std::visit applies a callable visitor to the currently held value.

8. Return multiple values safely using structured binding and std::tuple in C++

Code:

#include <iostream>
#include <tuple>
#include <string>

std::tuple<std::string, int, double> getPersonInfo() {
    return {"Alice", 28, 92.5};
}

int main() {
    auto [name, age, score] = getPersonInfo();
    std::cout << name << " (" << age << "): " << score << std::endl;
    return 0;
}

Output:

Alice (28): 92.5

Explanation: C++17 structured bindings syntax auto [a, b, c] unpacks tuples, pairs, or structures effortlessly.

9. Represent optional missing values using std::optional in C++

Code:

#include <iostream>
#include <optional>
#include <string>

std::optional<std::string> findUser(int id) {
    if (id == 1) return "Bob";
    return std::nullopt;
}

int main() {
    auto user = findUser(1);
    if (user.has_value()) {
        std::cout << "Found: " << user.value() << std::endl;
    }
    return 0;
}

Output:

Found: Bob

Explanation: std::optional provides a safe way to represent functions that may or may not return a value without relying on null pointers.

10. Create multithreaded tasks using std::async and std::future in C++

Code:

#include <iostream>
#include <future>

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

int main() {
    std::future<int> result = std::async(std::launch::async, computeSum, 15, 25);
    std::cout << "Async Sum: " << result.get() << std::endl;
    return 0;
}

Output:

Async Sum: 40

Explanation: std::async launches a task asynchronously in a separate thread and yields its eventual return value via std::future.

11. Solve the Two Sum problem using std::unordered_map in C++

Code:

#include <iostream>
#include <vector>
#include <unordered_map>

std::vector<int> twoSum(const std::vector<int>& nums, int target) {
    std::unordered_map<int, int> map;
    for (int i = 0; i < nums.size(); ++i) {
        int diff = target - nums[i];
        if (map.count(diff)) return {map, i};
        map[nums[i]] = i;
    }
    return {};
}

int main() {
    std::vector<int> indices = twoSum({2, 7, 11, 15}, 9);
    std::cout << indices[0] << ", " << indices[1] << std::endl;
    return 0;
}

Output:

0, 1

Explanation: std::unordered_map performs hash lookup in average O(1) time complexity to pair numbers matching the target sum.

12. Implement a thread-safe Singleton pattern using std::call_once in C++

Code:

#include <iostream>
#include <mutex>

class Singleton {
    Singleton() = default;
    static std::once_flag flag;
    static Singleton* instance;
public:
    static Singleton* getInstance() {
        std::call_once(flag, []() { instance = new Singleton(); });
        return instance;
    }
    void show() { std::cout << "Singleton instance\n"; }
};

std::once_flag Singleton::flag;
Singleton* Singleton::instance = nullptr;

int main() {
    Singleton::getInstance()->show();
    return 0;
}

Output:

Singleton instance

Explanation: std::call_once ensures that the initialization lambda runs exactly once across multiple concurrent threads.

13. Count character frequency in a string using std::map in C++

Code:

#include <iostream>
#include <map>
#include <string>

int main() {
    std::string text = "cpp";
    std::map<char, int> freq;
    for (char c : text) freq++;
    for (auto [ch, count] : freq) {
        std::cout << ch << ": " << count << std::endl;
    }
    return 0;
}

Output:

c: 1
p: 2

Explanation: Operates array subscript operator [] on std::map to implicitly insert missing characters and increment counts.

14. Use constexpr for compile-time calculation of factorial values in C++

Code:

#include <iostream>

constexpr long long factorial(int n) {
    return (n <= 1) ? 1 : n * factorial(n - 1);
}

int main() {
    constexpr long long fact5 = factorial(5);
    std::cout << "5! = " << fact5 << std::endl;
    return 0;
}

Output:

5! = 120

Explanation: The specifier constexpr forces expression evaluation at compile time instead of incurring runtime overhead.

15. Use std::string_view to avoid unnecessary string copies in C++

Code:

#include <iostream>
#include <string_view>

void printSV(std::string_view sv) {
    std::cout << sv << std::endl;
}

int main() {
    std::string str = "Zero Copy String View";
    printSV(str);
    printSV("Literal String");
    return 0;
}

Output:

Zero Copy String View
Literal String

Explanation: std::string_view provides a non-owning reference to string characters, eliminating dynamic memory allocations during passes.

16. Enforce template argument conditions using C++20 Concepts.

Code:

#include <iostream>
#include <concepts>

template <std::integral T>
T add(T a, T b) {
    return a + b;
}

int main() {
    std::cout << add(10, 20) << std::endl;
    return 0;
}

Output:

30

Explanation: std::integral concept restricts template evaluation strictly to integral parameters, producing clear compile errors on mismatch.

17. Perform Custom Object Comparison using C++20 Three-Way Comparison (Spaceship Operator).

Code:

#include <iostream>
#include <compare>

struct Point {
    int x, y;
    auto operator<=>(const Point&) const = default;
};

int main() {
    Point p1{1, 2}, p2{1, 3};
    std::cout << (p1 < p2 ? "p1 is smaller" : "p1 is equal or larger") << std::endl;
    return 0;
}

Output:

p1 is smaller

Explanation: Defaulted operator<=> auto-generates all relational operators (<, <=, ==, !=, >, >=) lexicographically.

18. Flatten or process generic data containers with std::accumulate in C++

Code:

#include <iostream>
#include <vector>
#include <numeric>

int main() {
    std::vector<int> nums = {1, 2, 3, 4, 5};
    int sum = std::accumulate(nums.begin(), nums.end(), 0);
    std::cout << "Sum: " << sum << std::endl;
    return 0;
}

Output:

Sum: 15

Explanation: std::accumulate from header <numeric> computes reduction sums across iterable ranges initialized with base values.

19. Extract minimum and maximum array elements in a single pass with std::minmax_element in C++

Code:

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> v = {3, 1, 9, -2, 7};
    auto [minIt, maxIt] = std::minmax_element(v.begin(), v.end());
    std::cout << "Min: " << *minIt << ", Max: " << *maxIt << std::endl;
    return 0;
}

Output:

Min: -2, Max: 9

Explanation: std::minmax_element scans through collection boundaries returning pairs of minimum and maximum iterators efficiently.

20. Implement RAII Lock Management using std::lock_guard in C++

Code:

#include <iostream>
#include <mutex>
#include <thread>

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: " << counter << std::endl;
    return 0;
}

Output:

Counter: 2

Explanation: std::lock_guard binds thread mutex acquisition to object lifetime scoping using standard RAII design principles.

21. Check for element existence using std::find and std::set in C++

Code:

#include <iostream>
#include <set>

int main() {
    std::set<int> s = {10, 20, 30};
    if (s.contains(20)) {
        std::cout << "20 exists in set" << std::endl;
    }
    return 0;
}

Output:

20 exists in set

Explanation: Modern C++20 introduces direct .contains() member function checks for binary trees and hash lookup containers.

22. Parse formatted string outputs using C++20 std::format.

Code:

#include <iostream>
#include <format>
#include <string>

int main() {
    std::string msg = std::format("User {} has {} points.", "Alice", 100);
    std::cout << msg << std::endl;
    return 0;
}

Output:

User Alice has 100 points.

Explanation: std::format offers Python-style string formatting capabilities with compile-time type safety.

23. Share instance ownership safely using std::shared_ptr and std::weak_ptr in C++

Code:

#include <iostream>
#include <memory>

int main() {
    auto shared = std::make_shared<int>(42);
    std::weak_ptr<int> weak = shared;

    if (auto temp = weak.lock()) {
        std::cout << "Value: " << *temp << std::endl;
    }
    return 0;
}

Output:

Value: 42

Explanation: std::weak_ptr references std::shared_ptr resources without incrementing reference counts, preventing memory reference cycles.

24. Apply transformations directly to vectors using std::transform in C++

Code:

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> src = {1, 2, 3};
    std::vector<int> dest(src.size());

    std::transform(src.begin(), src.end(), dest.begin(), [](int x) {
        return x * 10;
    });

    for (int n : dest) std::cout << n << " ";
    std::cout << std::endl;
    return 0;
}

Output:

10 20 30

Explanation: std::transform applies unary transformation operations to inputs and stores results into target iterators.

25. Demonstrate compile-time conditional checks using std::enable_if / SFINAE in C++

Code:

#include <iostream>
#include <type_traits>

template <typename T>
typename std::enable_if<std::is_integral<T>::value, void>::type
printType(T v) {
    std::cout << "Integer: " << v << std::endl;
}

int main() {
    printType(100);
    return 0;
}

Output:

Integer: 100

Explanation: std::enable_if conditionally removes template overloads from overload sets depending on type traits (SFINAE).

26. Construct elements directly inside containers using emplace_back in C++

Code:

#include <iostream>
#include <vector>
#include <string>

struct User {
    std::string name;
    int age;
    User(std::string n, int a) : name(n), age(a) {}
};

int main() {
    std::vector<User> users;
    users.emplace_back("Charlie", 35);
    std::cout << users[0].name << ": " << users[0].age << std::endl;
    return 0;
}

Output:

Charlie: 35

Explanation: emplace_back constructs objects in-place inside the vector memory buffer, avoiding temporary object construction copies.

27. Write generic templated code with C++ Variadic Templates

Code:

#include <iostream>

template<typename... Args>
auto sumAll(Args... args) {
    return (... + args);
}

int main() {
    std::cout << "Sum: " << sumAll(1, 2, 3, 4, 5) << std::endl;
    return 0;
}

Output:

Sum: 15

Explanation: Modern C++17 fold expressions (… + args) unpack parameter packs seamlessly into single binary operations.

28. Construct modern Priority Queue for Max-Heap operations in C++

Code:

#include <iostream>
#include <queue>

int main() {
    std::priority_queue<int> pq;
    pq.push(10);
    pq.push(30);
    pq.push(20);

    while (!pq.empty()) {
        std::cout << pq.top() << " ";
        pq.pop();
    }
    std::cout << std::endl;
    return 0;
}

Output:

30 20 10

Explanation: std::priority_queue arranges elements as a max-heap structure by default, keeping largest items at top.

29. Execute move semantics using std::move to transfer ownership in C++

Code:

#include <iostream>
#include <string>
#include <vector>

int main() {
    std::string str = "Resource Data";
    std::vector<std::string> vec;

    vec.push_back(std::move(str));

    std::cout << "Vector: " << vec[0] << std::endl;
    std::cout << "Original empty: " << (str.empty() ? "True" : "False") << std::endl;
    return 0;
}

Output:

Vector: Resource Data
Original empty: True

Explanation: std::move converts objects to rvalue references, transferring internal buffers without deep copying memory.

30. Read and write files cleanly using std::fstream with C++

Code:

#include <iostream>
#include <fstream>
#include <string>

int main() {
    std::ofstream outFile("data.txt");
    outFile << "C++ File Stream Work";
    outFile.close();

    std::ifstream inFile("data.txt");
    std::string content;
    std::getline(inFile, content);
    std::cout << "Read: " << content << std::endl;
    return 0;
}

Output:

Read: C++ File Stream Work

Explanation: Standard streams std::ofstream and std::ifstream encapsulate file I/O operations through standard stream operators.


If you liked the tutorial, spread the word and share the link and our website, Studyopedia, with others.


For Videos, Join Our YouTube Channel: Join Now


Recommended Posts

C++ Strings
Studyopedia Editorial Staff
contact@studyopedia.com

We work to create programming tutorials for all.

No Comments

Post A Comment