Skip to content

CPP Practice Questions

Prepare for CPP with more than an answer.

151 questions in the full set20 sample questionsUpdated Aug 11, 2025
Exam fee
$295 USD
Level
Professional
Valid for
lifetime
Domains covered on the exam 9
  1. Sequence Containers and Container Adapters13.25%
  2. Associative Containers13.25%
  3. Algorithms: Non-Modifying Sequence Operations13.25%
  4. Algorithms: Modifying Sequence Operations13.25%
  5. Algorithms: Sorting and Binary Search16.5%
  6. Algorithms: Merge, Heap, Min, Max16.5%
  7. STL Functional Objects and Utilities7%
  8. Advanced I/O7%
  9. Templates7%
  1. 1

    To efficiently find the median element in a large, unsorted std::vector without the overhead of fully sorting the entire collection, a developer should use the std::____ algorithm.

    Show answer details

    Correct answer: B

    std::nth_element is a partial sorting algorithm that rearranges elements in a range such that the element at the n-th position is the element that would be in that position in a fully sorted sequence. All of the elements before this n-th position are less than or equal to the elements after the n-th position. It has an average linear time complexity, making it much more efficient than a full sort (std::sort or std::stable_sort) for finding medians or other selection tasks.

  2. 2

    What is the precise output of the following C++ program that uses various stream manipulators to format a string?

    #include
    #include
    #include
    
    int main() {
    std::string product_id = "A42";
    std::cout << "|"
    << std::setw(8)
    << std::setfill('*')
    << std::left
    << product_id
    << "|";
    return 0;
    }
    
    Show answer details

    Correct answer: C

    The code configures the std::cout stream with three manipulators:

    1. std::setw(8): Sets the field width for the next output operation to 8 characters.
    2. std::setfill('*'): Sets the character used for padding to '*'.
    3. std::left: Sets the alignment to left-justify the output within the field.

    The string "A42" has 3 characters. It will be placed in an 8-character field. Because of std::left, it is aligned to the left, and the remaining 5 characters are padded with the fill character '*' on the right. The final output is therefore |A42*****|.

  3. 3

    The function adapters std::bind1st and std::bind2nd are deprecated in C++11 and removed in C++17. A developer maintaining legacy code needs to replace a call like std::find_if(v.begin(), v.end(), std::bind2nd(std::greater (), 10)); which finds the first element greater than 10. What is the simplest and most idiomatic modern C++ equivalent using a lambda expression?

    Show answer details

    Correct answer: C

    std::bind2nd(std::greater (), 10) (deprecated in C++11, removed in C++17) builds a unary predicate returning x > 10. The most concise, idiomatic lambda replacement is [](int x){ return x > 10; }. Wrapping std::greater () inside a lambda is equivalent but needlessly verbose, the std::bind(std::greater (), std::placeholders::_1, 10) form works but is not a lambda, and a lambda with a defaulted second parameter is not the intended unary predicate (default arguments on lambdas are allowed since C++14 but obscure the intent).

  4. 4

    Case Study:

    A development team is building a collaborative text editor. A core feature is the multi-level undo/redo functionality. The system must store the entire state of the document after each significant user action (e.g., typing a word, deleting a selection).

    Requirements:

    1. When a user performs an action, the new document state is added to a history manager.
    2. When the user clicks 'Undo', the most recent state must be retrieved and removed from the history, and the previous state becomes the current one.
    3. The system must support at least 100 levels of undo.
    4. Performance of adding a new state and performing an undo operation must be very fast (amortized constant time is required).
    5. Memory usage should be reasonably efficient, but performance is the primary concern.

    Which STL container is the most suitable choice to implement the history manager for the 'undo' stack?

    Show answer details

    Correct answer: B

    The undo functionality is a classic example of a Last-In, First-Out (LIFO) data structure, which is perfectly modeled by a stack. The std::stack container adapter provides the required push and pop operations, which map directly to adding a state and performing an undo. By default, std::stack uses std::deque as its underlying container. std::deque is an excellent choice here because it provides amortized constant-time push and pop operations at the back (which std::stack uses), satisfying the performance requirement. While a raw std::deque could be used, std::stack more clearly expresses the LIFO intent of the design.

  5. 5

    To use a custom class MyData as a key in a std::map that uses the default comparator, what are the minimal requirements that the class must fulfill? (Select TWO)

    Show answer details

    Correct answer: A, C

    std::map with the default comparator needs only two things from the key type: (1) the map must be able to store its own copy of the key in each node, so the key must be copy-constructible (or at least move-constructible, since C++11, if keys are always moved/emplaced in); (2) because the default comparator is std::less , which calls operator<, the class must provide an accessible operator< that forms a strict weak ordering. A default constructor, operator== (key equivalence is !(a<b) && !(b<a)), and a virtual destructor are not required.

    std::map with the default comparator needs only two things from the key type: (1) the map must be able to store its own copy of the key in each node, so the key must be copy-constructible (or at least move-constructible, since C++11, if keys are always moved/emplaced in); (2) because the default comparator is std::less , which calls operator<, the class must provide an accessible operator< that forms a strict weak ordering. A default constructor, operator== (key equivalence is !(a<b) && !(b<a)), and a virtual destructor are not required.

  6. 6

    A performance engineer is optimizing a logging system where log entries, represented by a custom LogEntry struct, are collected into a std::vector. The requirements state that after collection, the logs must be sorted chronologically by timestamp. If two entries have the exact same timestamp, their original insertion order must be preserved for forensic analysis. Which STL algorithm and comparator setup is the most appropriate and correct choice to meet these requirements?

    Show answer details

    Correct answer: C

    The key requirement is to preserve the original insertion order for entries with identical timestamps. The std::stable_sort algorithm is specifically designed for this purpose. It guarantees that the relative order of equivalent elements remains unchanged after sorting. std::sort does not provide this guarantee and may reorder elements with equal keys, which would violate the forensic analysis requirement. The other options are incorrect because std::partition only groups elements based on a predicate without fully sorting them, and std::sort on its own is insufficient.

  7. 7

    A software architect is designing a system component that models a production line. The component must handle frequent additions and removals of items from both the front and the back of the line. Additionally, random access to any item in the line using an index is a frequent operation for quality control checks. Which STL container is the most suitable choice for this scenario, considering all requirements?

    Show answer details

    Correct answer: E

    std::deque provides constant-time insertion and removal at both the front and the back (push_front/pop_front/push_back/pop_back) and constant-time random access via operator[]/at(), meeting every requirement. std::vector has O(1) random access and amortized O(1) back operations, but inserting or erasing at the front shifts every element (O(n)). std::list and std::forward_list offer no index access, and std::stack exposes only one end and no random access.

  8. 8

    A junior developer wrote the following code to remove all even numbers from a vector. After execution, they are surprised to find that while some even numbers are gone, the vector's size has not changed: the program prints Vector size: 9 followed by 1 3 5 7 9 6 7 8 9 (output from GCC; the last four values are unspecified). What is the fundamental misunderstanding in this code?

    #include
    #include
    #include
    
    int main() {
    std::vector numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9};
    std::remove_if(numbers.begin(), numbers.end(), [](int n){ return n % 2 == 0; });
    
    std::cout << "Vector size: " << numbers.size() << std::endl;
    for(int n : numbers) {
    std::cout << n << " ";
    }
    return 0;
    }
    
    Show answer details

    Correct answer: A

    std::remove_if (and std::remove) cannot alter the size of the container because it only has access to iterators, not the container object itself. It works by moving all elements that do not match the removal criteria to the front of the range and returns an iterator pointing one past the last element that was kept. The elements from this new logical end to the container's actual end are left in a valid but unspecified state. The correct way to physically remove the elements is to call the container's erase method with the iterator range returned by remove_if, a pattern known as the 'erase-remove idiom'.

  9. 9

    A developer is implementing a cache using std::map where the key is a custom struct UserSession. The code fails to compile with an error deep inside the STL headers related to comparison. What is the most likely missing component in the UserSession struct definition that is required for it to be a key in a std::map?

    #include
    #include
    
    struct UserSession {
    int userId;
    std::string sessionId;
    // Missing component
    };
    
    int main() {
    std::map userCache;
    // ... code to populate map
    return 0;
    }
    
    Show answer details

    Correct answer: A

    std::map is an ordered associative container, typically implemented as a red-black tree. To maintain order and determine the correct position for each key, it needs a way to compare two keys. By default, it uses std::less , which in turn calls operator< on the key objects. Therefore, the UserSession struct must provide a public operator< that establishes a strict weak ordering among its instances. Alternatively, a custom comparator function object could be provided as a template argument to the map, but the most common solution is to overload operator<.

  10. 10

    Case Study:

    A financial technology company is developing a high-frequency trading platform. The system receives two separate, large streams of real-time trade data from two different exchanges, exchangeA_trades and exchangeB_trades. Both streams are delivered as sorted std::vector objects, ordered by trade ID. The Trade struct has a unique tradeId and other financial data.

    The system needs to perform three critical tasks with maximum efficiency:

    1. Create a single, consolidated list of all trades from both exchanges, sorted by tradeId.
    2. Generate a report of trades that appeared on both exchanges (i.e., common trades).
    3. Generate a report of trades that appeared on exchangeA but not on exchangeB.

    Given that the input vectors are already sorted and performance is paramount, which sequence of STL algorithms represents the most efficient approach to accomplish all three tasks?

    Show answer details

    Correct answer: D

    This approach is the most efficient because it leverages the fact that the input vectors are already sorted. std::merge, std::set_intersection, and std::set_difference are all linear time O(N+M) algorithms when operating on sorted ranges. std::merge efficiently creates the consolidated list. std::set_intersection produces the common trades, and std::set_difference produces the trades in the first range but not the second. Any approach involving re-sorting (like concatenation followed by std::sort) would be less efficient, with a complexity of O((N+M)log(N+M)).

Create an account to continue.