CPP Practice Questions
Prepare for CPP with more than an answer.
- Exam fee
- $295 USD
- Level
- Professional
- Valid for
- lifetime
Domains covered on the exam 9
- Sequence Containers and Container Adapters13.25%
- Associative Containers13.25%
- Algorithms: Non-Modifying Sequence Operations13.25%
- Algorithms: Modifying Sequence Operations13.25%
- Algorithms: Sorting and Binary Search16.5%
- Algorithms: Merge, Heap, Min, Max16.5%
- STL Functional Objects and Utilities7%
- Advanced I/O7%
- Templates7%
- 1
To efficiently find the median element in a large, unsorted
std::vectorwithout the overhead of fully sorting the entire collection, a developer should use thestd::____algorithm.Show answer details
Correct answer: B
std::nth_elementis 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::sortorstd::stable_sort) for finding medians or other selection tasks. - 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::coutstream with three manipulators:std::setw(8): Sets the field width for the next output operation to 8 characters.std::setfill('*'): Sets the character used for padding to '*'.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 ofstd::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
The function adapters
std::bind1standstd::bind2ndare deprecated in C++11 and removed in C++17. A developer maintaining legacy code needs to replace a call likestd::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 returningx > 10. The most concise, idiomatic lambda replacement is[](int x){ return x > 10; }. Wrappingstd::greater ()inside a lambda is equivalent but needlessly verbose, thestd::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
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:
- When a user performs an action, the new document state is added to a history manager.
- 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.
- The system must support at least 100 levels of undo.
- Performance of adding a new state and performing an undo operation must be very fast (amortized constant time is required).
- 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::stackcontainer adapter provides the requiredpushandpopoperations, which map directly to adding a state and performing an undo. By default,std::stackusesstd::dequeas its underlying container.std::dequeis an excellent choice here because it provides amortized constant-time push and pop operations at the back (whichstd::stackuses), satisfying the performance requirement. While a rawstd::dequecould be used,std::stackmore clearly expresses the LIFO intent of the design. - 5
To use a custom class
MyDataas a key in astd::mapthat uses the default comparator, what are the minimal requirements that the class must fulfill? (Select TWO)Show answer details
Correct answer: A, C
std::mapwith 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 isstd::less, which callsoperator<, the class must provide an accessibleoperator<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::mapwith 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 isstd::less, which callsoperator<, the class must provide an accessibleoperator<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
A performance engineer is optimizing a logging system where log entries, represented by a custom
LogEntrystruct, are collected into astd::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_sortalgorithm is specifically designed for this purpose. It guarantees that the relative order of equivalent elements remains unchanged after sorting.std::sortdoes not provide this guarantee and may reorder elements with equal keys, which would violate the forensic analysis requirement. The other options are incorrect becausestd::partitiononly groups elements based on a predicate without fully sorting them, andstd::sorton its own is insufficient. - 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::dequeprovides 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 viaoperator[]/at(), meeting every requirement.std::vectorhas O(1) random access and amortized O(1) back operations, but inserting or erasing at the front shifts every element (O(n)).std::listandstd::forward_listoffer no index access, andstd::stackexposes only one end and no random access. - 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: 9followed by1 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(andstd::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'serasemethod with the iterator range returned byremove_if, a pattern known as the 'erase-remove idiom'. - 9
A developer is implementing a cache using
std::mapwhere the key is a custom structUserSession. The code fails to compile with an error deep inside the STL headers related to comparison. What is the most likely missing component in theUserSessionstruct definition that is required for it to be a key in astd::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::mapis 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 usesstd::less, which in turn callsoperator<on the key objects. Therefore, theUserSessionstruct must provide a publicoperator<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 overloadoperator<. - 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_tradesandexchangeB_trades. Both streams are delivered as sortedstd::vectorobjects, ordered by trade ID. TheTradestruct has a uniquetradeIdand other financial data.The system needs to perform three critical tasks with maximum efficiency:
- Create a single, consolidated list of all trades from both exchanges, sorted by
tradeId. - Generate a report of trades that appeared on both exchanges (i.e., common trades).
- Generate a report of trades that appeared on
exchangeAbut not onexchangeB.
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, andstd::set_differenceare all linear time O(N+M) algorithms when operating on sorted ranges.std::mergeefficiently creates the consolidated list.std::set_intersectionproduces the common trades, andstd::set_differenceproduces the trades in the first range but not the second. Any approach involving re-sorting (like concatenation followed bystd::sort) would be less efficient, with a complexity of O((N+M)log(N+M)). - Create a single, consolidated list of all trades from both exchanges, sorted by
