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.
- 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 forconst 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 typeconst char[6], which decays toconst char*. Theprocess(const char*)function is an exact match for this type. The template functionprocesscould also be instantiated withTasconst char*, but the non-template overload is a better match and will be chosen without hesitation. - Question 2Intermediate
Algorithms: Non-Modifying Sequence Operations · Using sequence searching algorithms like std::find_end
Given a
std::vectornamedsourceand a smallerstd::vectornamedpattern, what is the correct way to use an STL algorithm to find the beginning of the last occurrence of thepatternsequence within thesourcesequence?Show answer & explanation
Correct answer: A
The
std::find_endalgorithm 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::searchfinds the first occurrence. Using reverse iterators withstd::searchis 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. - Question 3Beginner
Advanced I/O · Persistence of stream manipulators
True or False: Once the
std::fixedstream manipulator is used onstd::cout, it remains in effect for all subsequent floating-point output tostd::coutuntil it is explicitly cleared by another manipulator likestd::defaultfloat.Show answer & explanation
Correct answer: A
Manipulators like
std::fixed,std::scientific,std::boolalpha, andstd::setprecisionmodify 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 likestd::setwonly affect the very next output operation. - 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
datavector after thestd::transformalgorithm 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
datato{1, 2, 3, 4, 5}usingstd::iota. Thestd::transformalgorithm is then used for an in-place modification (source and destination iterators are the same). The lambda function captures themultipliervariable (value 3) by value. It iterates through each element ofdata. If an element (val) is odd (val % 2 != 0), it returnsval * multiplier; otherwise, it returns the originalval.- 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}.
- 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_boundalgorithm returns an iterator pointing to the first element in the range[first, last)which does not compare less thanval. 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 for40. The first element that is not less than40is50. Therefore, the iteratoritwill point to the element50, and dereferencing it will print50. - 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
3from astd::vectorinside 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
3from the vector?Show answer & explanation
Correct answer: D
When
v.erase(it)is called on astd::vector, it invalidates all iterators at or after the point of erasure, includingititself. Incrementing the invalidated iteratoritin theforloop's increment step (++it) leads to undefined behavior, often a crash. Theerasemethod forstd::vectorconveniently 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. - 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
adminsandpower_users, what will be the content of theresultvector 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_intersectionalgorithm 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 elements205and301are present in both theadminsandpower_usersvectors. Therefore, theresultvector will contain{205, 301}. - Question 8Advanced
Algorithms: Modifying Sequence Operations · Understanding the ordering guarantees of std::partition
A developer uses
std::partitionto 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 operationstd::partition(v.begin(), v.end(), [](int n){ return n % 2 != 0; });is executed?Show answer & explanation
Correct answer: C
std::partitionreorders the range so that every element for which the predicate returnstrue(the odd numbers) precedes every element for which it returnsfalse(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. - 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] = valuedoes two things: if the key is absent it first inserts a value-initializedstd::stringand then assignsvalueto 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 returnedstd::pairhassecond == false.emplacewould also avoid overwriting, so it is not 'the only correct way'. - 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_ifto 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_ifalgorithm iterates through the range specified byscores.begin()andscores.end(). For each element, it applies the provided lambda function as a predicate. The lambda capturespassing_grade(value 90) and returnstrueif a score is greater than or equal to 90. The algorithm returns the total number of times the predicate returnedtrue.- 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 outputs3.
Ready for the real thing?
The full CPP simulator has every exam-style question, timed mode, and instant scoring.