CPP Sample Questions

CPP Sample Questions & Answers

Sorting and binary-search algorithms tie with merge, heap, set and min/max operations for the top weight, alongside STL containers both sequence and associative, algorithms that modify or leave sequences unchanged, templates, stream I/O, and function objects.

Launch the full CPP simulator →

Showing 10 of 20 free samples.

  1. Question 1Advanced

    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;
    }
    
    Show answer & 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.

  2. Question 2Intermediate

    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?

    Show answer & 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.

  3. Question 3Beginner

    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.

    Show answer & 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.

  4. Question 4Intermediate

    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;
    }
    
    Show answer & 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}.
  5. Question 5Intermediate

    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?

    Show answer & 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.

  6. Question 6Intermediate

    Sequence Containers and Container Adapters · Correctly erasing elements from a vector while iterating

    A developer is attempting to remove all elements with the value 3 from a std::vector inside a loop. Their initial code causes a crash.

    // Problematic Code
    for (auto it = v.begin(); it != v.end(); ++it) {
    if (*it == 3) {
    v.erase(it); // This line is problematic
    }
    }
    

    Which of the following loops correctly and safely erases all elements with the value 3 from the vector?

    Show answer & explanation

    Correct answer: D

    When v.erase(it) is called on a std::vector, it invalidates all iterators at or after the point of erasure, including it itself. Incrementing the invalidated iterator it in the for loop's increment step (++it) leads to undefined behavior, often a crash. The erase method for std::vector conveniently returns a new valid iterator pointing to the element that followed the erased element. The correct pattern is to capture this returned iterator and only increment the iterator manually when no erasure occurs.

  7. Question 7Intermediate

    Algorithms: Merge, Heap, Min, Max · Using std::set_intersection to find common elements in sorted ranges

    A program needs to find the common elements between two sorted lists of user IDs. Given the two input vectors admins and power_users, what will be the content of the result vector after the following code is executed?

    #include
    #include
    #include
    #include
    
    int main() {
    std::vector admins = {101, 205, 301, 450};
    std::vector power_users = {205, 301, 512, 620};
    std::vector result;
    
    std::set_intersection(admins.begin(), admins.end(),
    power_users.begin(), power_users.end(),
    std::back_inserter(result));
    
    for (int id : result) {
    std::cout << id << " ";
    }
    return 0;
    }
    
    graph TD subgraph Input A[admins: 101, 205, 301, 450] B[power_users: 205, 301, 512, 620] end Input --> |std::set_intersection| Output(result: ?)
    Show answer & explanation

    Correct answer: B

    The std::set_intersection algorithm constructs a sorted range that is the intersection of two sorted source ranges. It iterates through both input ranges and copies elements that are present in both to the destination. In this case, the elements 205 and 301 are present in both the admins and power_users vectors. Therefore, the result vector will contain {205, 301}.

  8. Question 8Advanced

    Algorithms: Modifying Sequence Operations · Understanding the ordering guarantees of std::partition

    A developer uses std::partition to reorder a vector of integers so that all odd numbers appear before all even numbers. Given the initial vector {8, 3, 7, 2, 5, 4, 6, 1}, which of the following is a possible state for the vector after the operation std::partition(v.begin(), v.end(), [](int n){ return n % 2 != 0; }); is executed?

    Show answer & explanation

    Correct answer: C

    std::partition reorders the range so that every element for which the predicate returns true (the odd numbers) precedes every element for which it returns false (the even numbers). It does not guarantee the relative order within either group. {1, 3, 7, 5, 2, 4, 6, 8} satisfies this (and is what GCC's implementation produces). {1, 3, 7, 2, 5, 4, 6, 8} and {3, 7, 5, 2, 1, 8, 4, 6} each have an even number before an odd number, so they are not partitioned, and no single result is 'always' guaranteed for groups whose order is unspecified.

  9. Question 9Intermediate

    Associative Containers · Performance comparison of map insertion methods

    When populating a std::map , a developer has a large dataset where it is common for keys to already exist in the map. They want to avoid overwriting existing values. Which of the following methods is generally more performant for this specific use case and why?

    Show answer & explanation

    Correct answer: D

    my_map[key] = value does two things: if the key is absent it first inserts a value-initialized std::string and then assigns value to it (default construction + assignment); if the key is present it overwrites the existing value, which violates the requirement. my_map.insert({key, value}) performs one lookup and, only when the key is absent, creates the node directly from the pair (copy/move-constructing the mapped value - no default construction followed by assignment). When the key already exists nothing is inserted or overwritten and the returned std::pair has second == false. emplace would also avoid overwriting, so it is not 'the only correct way'.

  10. Question 10Beginner

    Algorithms: Non-Modifying Sequence Operations · Using std::count_if with a predicate

    What is the output of the following program that uses std::count_if to count elements satisfying a specific condition?

    #include
    #include
    #include
    
    int main() {
    std::vector scores = {88, 95, 67, 72, 99, 58, 91};
    int passing_grade = 90;
    
    auto high_scores = std::count_if(scores.begin(), scores.end(),
    [=](int score) {
    return score >= passing_grade;
    });
    
    std::cout << high_scores;
    
    return 0;
    }
    
    Show answer & explanation

    Correct answer: C

    The std::count_if algorithm iterates through the range specified by scores.begin() and scores.end(). For each element, it applies the provided lambda function as a predicate. The lambda captures passing_grade (value 90) and returns true if a score is greater than or equal to 90. The algorithm returns the total number of times the predicate returned true.

    • 88 >= 90 is false
    • 95 >= 90 is true
    • 67 >= 90 is false
    • 72 >= 90 is false
    • 99 >= 90 is true
    • 58 >= 90 is false
    • 91 >= 90 is true
      The predicate returns true for three elements (95, 99, 91), so the program outputs 3.

Ready for the real thing?

The full CPP simulator has every exam-style question, timed mode, and instant scoring.

Go to the CPP simulator →