C++ Certified Professional Programmer Free Sample Questions

Description

Covers sequence and associative STL containers, non-modifying and modifying sequence algorithms, sorting and binary search, merge and heap operations, function objects, stream I/O, and templates.

20 free sample questions151 in the full practice test

Try simulator

CPP Sample Questions

  1. Question 1

    Advanced

    Algorithms: Sorting and Binary Search · Applying stable sorting algorithms for complex criteria

    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?

    Answer and explanation

    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.

  2. Question 2

    Intermediate

    Sequence Containers and Container Adapters · Choosing the appropriate sequence container based on performance characteristics

    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?

    Answer and explanation

    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.

  3. Question 3

    Intermediate

    Algorithms: Modifying Sequence Operations · Understanding the behavior of std::remove_if and the erase-remove idiom

    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;
    }
    
    Answer and explanation

    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'.

  4. Question 4

    Intermediate

    Associative Containers · Requirements for custom key types in ordered associative containers

    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;
    }
    
    Answer and explanation

    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<.

  5. Question 5

    Advanced

    Algorithms: Merge, Heap, Min, Max · Applying set and merge algorithms for data reconciliation

    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?

    Answer and explanation

    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)).

  6. Question 6

    Advanced

    Templates · Overload resolution with function templates and non-template functions

    A library designer has provided a generic template function process() and a specific overload for const char*. A developer then calls this function with a string literal. What is the output of the following program?

    #include
    
    template
    void process(T value) {
    std::cout << "Template version\n";
    }
    
    void process(const char* value) {
    std::cout << "Non-template overload\n";
    }
    
    int main() {
    process("hello");
    return 0;
    }
    
    Answer and explanation

    Correct answer: A

    During C++ overload resolution, the compiler follows a set of rules to select the best function to call. A non-template function that is a perfect match for the argument types is preferred over a template instantiation. In this case, the string literal "hello" has the type const char[6], which decays to const char*. The process(const char*) function is an exact match for this type. The template function process could also be instantiated with T as const char*, but the non-template overload is a better match and will be chosen without hesitation.

  7. Question 7

    Intermediate

    Algorithms: Non-Modifying Sequence Operations · Using sequence searching algorithms like std::find_end

    Given a std::vector named source and a smaller std::vector named pattern, what is the correct way to use an STL algorithm to find the beginning of the last occurrence of the pattern sequence within the source sequence?

    Answer and explanation

    Correct answer: A

    The std::find_end algorithm is specifically designed for this purpose. It searches for the last occurrence of a sub-sequence within a larger sequence. It takes iterators for the range to be searched and iterators for the pattern to search for. std::search finds the first occurrence. Using reverse iterators with std::search is tricky because it finds the first occurrence in the reversed sequence, which corresponds to the last occurrence but returns a reverse iterator that needs to be converted back correctly.

  8. Question 8

    Beginner

    Advanced I/O · Persistence of stream manipulators

    True or False: Once the std::fixed stream manipulator is used on std::cout, it remains in effect for all subsequent floating-point output to std::cout until it is explicitly cleared by another manipulator like std::defaultfloat.

    Answer and explanation

    Correct answer: A

    Manipulators like std::fixed, std::scientific, std::boolalpha, and std::setprecision modify the internal state of the stream object. This state is persistent and affects all subsequent I/O operations on that stream until the state is explicitly changed by another manipulator. In contrast, manipulators like std::setw only affect the very next output operation.

  9. Question 9

    Intermediate

    STL Functional Objects and Utilities · Using lambda expressions with STL algorithms

    Analyze the following C++ code. What will be the final contents of the data vector after the std::transform algorithm is executed?

    #include
    #include
    #include
    #include
    
    int main() {
    std::vector data(5);
    std::iota(data.begin(), data.end(), 1); // Fills data with 1, 2, 3, 4, 5
    
    int multiplier = 3;
    std::transform(data.begin(), data.end(), data.begin(),
    [multiplier](int val) {
    if (val % 2 != 0) {
    return val * multiplier;
    }
    return val;
    });
    
    for (int val : data) {
    std::cout << val << " ";
    }
    
    return 0;
    }
    
    Answer and explanation

    Correct answer: B

    The code first initializes the vector data to {1, 2, 3, 4, 5} using std::iota. The std::transform algorithm is then used for an in-place modification (source and destination iterators are the same). The lambda function captures the multiplier variable (value 3) by value. It iterates through each element of data. If an element (val) is odd (val % 2 != 0), it returns val * multiplier; otherwise, it returns the original val.

    • 1 is odd: 1 * 3 = 3
    • 2 is even: 2
    • 3 is odd: 3 * 3 = 9
    • 4 is even: 4
    • 5 is odd: 5 * 3 = 15
      Therefore, the final state of the vector is {3, 2, 9, 4, 15}.
  10. Question 10

    Intermediate

    Algorithms: Sorting and Binary Search · Understanding the behavior of std::lower_bound

    A developer is searching for a value in a sorted std::vector . If the exact value is not found, they need to find the position where the value could be inserted while maintaining the sort order. Consider the following code:

    #include
    #include
    #include
    
    int main() {
    std::vector data = {10, 20, 30, 50, 60};
    auto it = std::lower_bound(data.begin(), data.end(), 40);
    std::cout << *it;
    return 0;
    }
    

    What is the output of this program?

    Answer and explanation

    Correct answer: C

    The std::lower_bound algorithm returns an iterator pointing to the first element in the range [first, last) which does not compare less than val. In a sorted range, this is the correct insertion point to maintain order. In the vector {10, 20, 30, 50, 60}, the algorithm is searching for 40. The first element that is not less than 40 is 50. Therefore, the iterator it will point to the element 50, and dereferencing it will print 50.

Register free for 10 more questions

Or unlock all 151 CPP questions with explanations, timed mode and flashcards.