Skip to content
Tutorials Center
My learning

Topics

Lesson 168 of 171 ยท Practice and Review

C++ Programs: OOP and STL Recipes

C++ class and STL recipes with output: singleton, interface, complex class with ++ and --, vector of pairs to map, merging maps, multiset, permutations.

Two kinds of everyday C++ code are worth practising as complete programs: small classes that show a design idea, and short recipes that glue standard containers together. This page has eight of them. The first four use classes (a singleton, an interface, a complex number with overloaded operators); the rest use maps, multisets, std::next_permutation and a priority queue.

Every program is complete and runnable. If a concept is unfamiliar, the lesson links point to the full explanation: abstract classes, operator overloading, map, multiset and stack, queue and priority queue. The design patterns lesson goes much deeper than the singleton shown here.

Classes

1. A singleton

A singleton is a class that has exactly one instance, reachable from anywhere. The safest modern form is a function-local static: C++ guarantees that it is initialized once, even when several threads call the function at the same moment, so no locking code is needed. Deleting the copy operations stops anyone from making a second instance by copying.

C++ 1. Singleton

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Treat singletons with care: they are global state in disguise and make code harder to test. They suit things that are truly unique, such as a logger or a configuration holder.

2. An interface

C++ has no interface keyword. An interface is an abstract class with only pure virtual functions and a virtual destructor. Code that uses a Shape& works with any class that implements the interface.

C++ 2. Interface with pure virtual functions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

3. A complex number class with ++ and --

Prefix ++c modifies the object and returns a reference to it. Postfix c++ takes a dummy int parameter, returns the old value, and is usually written in terms of the prefix form. Here "increment" adds 1 to the real part. The operator<< is a friend so it can print the private fields.

C++ 3. Complex with ++ and --

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Containers

4. A vector of pairs into a map

A std::map can be built straight from a range of pairs. When the vector holds duplicate keys, the constructor keeps the first one; if you want the last value or a combined value, loop and use operator[] or insert_or_assign.

C++ 4. Vector of pairs to map

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

5. Merge two maps

merge (C++17) moves nodes from one map to another without copying; keys that already exist in the destination stay behind in the source. To combine values instead (for example, add counts), loop over one map and update the other.

C++ 5. Merging maps

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

6. Multiset frequency and a custom comparator

A std::multiset keeps duplicates in sorted order, and count(x) reports how many copies there are. Passing std::greater<> as the comparator flips the order. Walk the distinct values with upper_bound to jump past all duplicates of a value in logarithmic time.

C++ 6. Multiset frequencies

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

7. All permutations

std::next_permutation rearranges a range into the next lexicographically larger order and returns false after the last one (wrapping to the first). Start from a sorted range to visit every permutation exactly once; with duplicate values, each distinct arrangement is produced once.

C++ 7. Permutations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

8. A reverse (min) priority queue

std::priority_queue is a max-heap: top() is the largest element. To make a min-heap, give it a std::vector as the container and std::greater<> as the comparison.

C++ 8. Min-heap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is a function-local static a safe way to build a singleton in modern C++?

    Since C++11 the compiler guarantees that a local static is initialized exactly once, even with concurrent callers.
  2. 2. What distinguishes the postfix operator++ from the prefix one in a class?

    The unused int parameter selects the postfix form, which returns a copy of the object as it was before the increment.
  3. 3. Constructing a std::map from a vector of pairs with duplicate keys keeps which value?

    Range insertion skips keys that already exist, so the first value for each key wins.
  4. 4. How do you get a min-heap from std::priority_queue?

    The default comparator makes a max-heap; greater<> reverses the order so the smallest element is on top.

Summary

  • A function-local static gives a thread-safe singleton; delete copying and keep the constructor private.
  • An interface is an abstract class of pure virtual functions plus a virtual destructor.
  • Prefix ++ returns *this by reference; postfix ++ takes a dummy int and returns the old value.
  • Building a map from a vector of pairs keeps the first duplicate; insert_or_assign keeps the last.
  • map::merge moves non-conflicting nodes; combine values with a loop.
  • multiset keeps duplicates sorted, std::next_permutation walks permutations from a sorted start, and std::greater<> turns a priority queue into a min-heap.

Next: C++ Programs: Files and Dates.