Exam Information
Free practice questions with explanations
C++ Institute CPP Practice Questions
Answer a question to see the correct answer and the explanation, or click Show answer. Newest questions first.
- Questions
- 18
- Answered
- 0
- Correct
- 0
- Score
- -
-
1 Question 1 Single choice Modifying STL algorithms
A logging service stores log records in a std::vector. Before archiving, a developer must remove every empty string and then shrink the vector so that its size reflects the remaining records. The team wants to avoid an extra copy of the data. Which approach is correct?
Correct Answer: AExplanationstd::remove_if only moves the retained elements forward and returns the new logical end; it does not change the container size. The erase-remove idiom, calling erase from the returned iterator to end(), is what actually shrinks the vector without an extra copy. Relying on size() after remove_if is wrong because the container still holds its original number of elements. std::copy_if works but allocates and copies the whole data set, which the team wants to avoid. std::unique only removes consecutive duplicates, not empty strings.
-
2 Question 2 Single choice Non-modifying STL algorithms
A telemetry module keeps a std::list of sensor readings sorted in arrival order. An engineer needs to know whether the subsequence {42, 7, 19} appears anywhere in the list, in that exact order but not necessarily contiguous. The list must not be modified and the code should be as clear as possible. Which standard algorithm should be used?
Correct Answer: BExplanationstd::search looks for the first occurrence of a pattern as a subsequence, which is what the sensor check requires. It is a non-modifying algorithm that works with forward iterators, so std::list is compatible. find_first_of only tests membership of any pattern element and ignores order. includes requires both ranges to be sorted, which the readings are not. find_end finds the last occurrence rather than whether the pattern exists, and the requirement is a simple existence check, so search is the cleanest fit.
-
3 Question 3 Single choice Sorting STL operations
A trading application stores orders in a std::vector sorted by price using operator
Correct Answer: DExplanationstd::equal_range, used with a comparator that compares only the price field, returns the bounding iterator pair in logarithmic time on a sorted range. std::binary_search only returns a bool, so it cannot supply the matching positions. Re-sorting on every query violates the logarithmic requirement. random_shuffle destroys the sorted order that binary search depends on, and the proposal would break the container invariant.
-
4 Question 4 Single choice STL advanced I/O
A data import tool reads comma-separated records from a file and must parse each line into a struct containing a name and an integer quantity. Lines are read with std::getline into a std::string. The team wants to convert each line's numeric field without exceptions for malformed data and without locale surprises. Which approach meets these constraints?
Correct Answer: CExplanationA std::istringstream lets the parser extract fields with operator>> and inspect failbit after each extraction, so malformed data is detected without exceptions. std::atoi returns zero for invalid input and reports no error, so malformed quantities would be silently accepted. Redirecting std::cin via rdbuf is an awkward hack that does not fit file parsing. std::stoi does throw, which violates the no-exception constraint.
-
5 Question 5 Single choice STL Associative containers
A permissions service maps each user ID to a set of granted permission strings. Users can hold several permissions, duplicates must be rejected, and the team needs to iterate permissions in a deterministic alphabetical order. Lookups by user ID must be logarithmic. Which container design is most appropriate?
Correct Answer: AExplanationA std::set as the mapped type rejects duplicate permissions and keeps them in sorted order, while std::map gives logarithmic lookup by user ID. The multimap option allows multiple entries per key but gives no structure preventing duplicate permission strings, and grouping per user is awkward. The unordered_map option sacrifices deterministic ordering unless sorted each time. The multiset explicitly keeps duplicates, contrary to the requirement.
-
6 Question 6 Multiple choice STL Associative containers
A developer is reviewing a program that stores customer records in a std::set, where Customer is a struct with an id field and a name field. Records with the same id but different names must be treated as the same customer, and the set must hold one entry per id. Which two statements about this design are correct? (Choose two.)
Correct Answer: C, EExplanationstd::set uses an ordering to decide equivalence, so an id-only comparator makes records with the same id equivalent and insert then reports the existing element, returning false in the second member of the pair. That confirms one entry per id. std::unordered_set still needs a hash and equality for Customer, so it does not remove the requirement. std::multiset allows multiple equivalent elements, so it fails the one-per-id constraint.
-
7 Question 7 Single choice STL Sequential containers
A game engine stores pending animation events in a std::deque. New events are added at the back by a producer thread that is synchronised separately, and the consumer always removes the oldest event from the front. The engine also occasionally needs random access by index for debugging. Which statement about this container choice is correct?
Correct Answer: BExplanationstd::deque offers amortised constant-time insertion and removal at both ends and constant-time random access by index, matching all three patterns. std::list provides no random access, so the debugging requirement fails. std::vector has no efficient pop_front, since removing the first element shifts the rest. std::queue is an adapter that deliberately hides random access, so it cannot provide index access.
-
8 Question 8 Single choice STL Sequential containers
A scheduling component keeps a std::priority_queue of tasks ordered by a priority field. Tasks with equal priority must be dispatched in the order they were enqueued, and the team must not change the container semantics beyond this requirement. A reviewer suggests replacing the comparator with one that compares only priority. Why is this insufficient, and what should be done?
Correct Answer: AExplanationpriority_queue is a heap, which gives no guarantee about the relative order of equivalent elements, so a priority-only comparator cannot enforce FIFO among equal priorities. Adding a monotonically increasing sequence number and comparing it as a tiebreaker produces a deterministic total order. Reversing the comparator alone does not fix ties. priority_queue does honour its comparator, so the second option is false. std::stack gives LIFO behaviour and does not solve ordering by priority.
-
9 Question 9 Single choice STL utilities and functional library
A reporting module must sum the total sales of every item in a std::vector that exceeds a threshold read from configuration at runtime. The team wants the threshold captured without writing a named functor class, and the code must compile under C++11. Which approach best meets these constraints?
Correct Answer: AExplanationA lambda in C++11 captures the runtime threshold directly, and std::accumulate with a binary operation can add only qualifying values in one pass. std::bind1st is deprecated in C++11 and removed in C++17, so it fails the portability intent. std::multiplies cannot express threshold filtering. A global variable with a function pointer works but ignores the stated preference for capturing the value locally and is poorer design.
-
10 Question 10 Dropdown Templates
A library author is writing a generic function that returns the larger of two values of the same type, and wants the compiler to deduce the type from the arguments at each call site without requiring explicit template arguments. Complete the declaration so the function template is correct and each argument is taken by const reference.
Choose the correct value for each blank.
T maximum(const T& a, const T& b) { return a > b ? a : b; } where the declaration begins with and the parameter type is named TCorrect Answer:template T maximum(const T& a, const T& b) { return a > b ? a : b; } where the declaration begins with template and the parameter type is named T
ExplanationThe declaration needs a template header of the form template , which lets the compiler deduce T from the call arguments. The second blank is conceptually the same header keyword, so the second blank reads the template keyword that introduces the parameter list. Placing the header after the return type keyword is not valid C++. Typedef and static forms do not declare a template. auto is a return type placeholder, not a template parameter introducer.
-
11 Question 11 Order list Modifying STL algorithms
A data pipeline holds a std::vector of raw measurements. Duplicate consecutive values must be removed, then the remaining values must be reversed in place, and finally the vector must be trimmed so its size equals the number of distinct consecutive runs. Arrange the steps in the correct order.
Drag the steps into the correct order, or use the arrows.
- Sort the vector with std::sort so that duplicates become adjacent before removal
- Call std::reverse over the range from begin() to the new end so that the remaining values are reversed in place
- Call std::unique on the vector to move duplicate consecutive values to the end and obtain the new logical end
- Call erase from the returned iterator to end() so that the vector size matches the remaining values
Correct Answer:- Call std::unique on the vector to move duplicate consecutive values to the end and obtain the new logical end
- Call erase from the returned iterator to end() so that the vector size matches the remaining values
- Call std::reverse over the range from begin() to the new end so that the remaining values are reversed in place
- Sort the vector with std::sort so that duplicates become adjacent before removal
Explanationstd::unique only removes consecutive duplicates, so the vector must first be sorted only if duplicates were non-adjacent; the pipeline requires consecutive removal, so sorting is wrong here and the correct sequence is unique, erase to the logical end, then reverse. The intended ordering is therefore: call std::unique first, erase from the returned iterator to end, then reverse the trimmed range. Sorting would reorder the data and destroy the requested run-based semantics, so it must not be included in the sequence.
-
12 Question 12 Drag and drop Sorting STL operations
A risk engine holds a sorted std::vector of exposure values. Match each requirement to the STL algorithm that satisfies it.
Drag each item onto its matching target. On a phone: tap an item, then tap a target.
Test whether a value is present in the sorted range without needing its positionFind the first position at which a value could be inserted without breaking sort orderShuffle the elements into a random order for a Monte Carlo sampling runstd::inplace_mergestd::lower_boundstd::random_shufflestd::stable_sortstd::binary_searchCorrect Answer:- Find the first position at which a value could be inserted without breaking sort order → std::lower_bound
- Shuffle the elements into a random order for a Monte Carlo sampling run → std::random_shuffle
- Test whether a value is present in the sorted range without needing its position → std::binary_search
Explanationstd::lower_bound returns the first position where a value could be inserted while preserving order, which is exactly the insertion-point requirement. random_shuffle produces a random permutation, serving the sampling run. binary_search gives a boolean presence test on a sorted range. stable_sort and inplace_merge are sorting or merging algorithms that do not answer these three specific needs.
-
13 Question 13 Single choice Non-modifying STL algorithms
A quality-control script inspects a std::vector of batch counts. The team needs the index of the first position where two adjacent values are equal, and must not change the vector. A developer writes a loop using std::find with a comparator. Which standard algorithm is the appropriate replacement?
Correct Answer: DExplanationstd::adjacent_find is designed to find the first pair of consecutive equal elements and returns an iterator, matching the requirement precisely and without modifying the vector. std::mismatch compares two ranges rather than neighbours in one range. std::count_if counts matches without locating the first adjacent pair. std::equal compares whole ranges for equality and does not search a single range for adjacent duplicates.
-
14 Question 14 Single choice STL advanced I/O
A logging library must write fixed-width records to a file so that a downstream parser can read columns by position. Each numeric field must be right-aligned in a width of 8 characters with two decimal places. The file is opened in text mode and the output stream's formatting must not leak into later writes to the same stream. Which approach satisfies the requirements?
Correct Answer: BExplanationstd::setw applies only to the next formatted output operation, so it must be set before each field, while std::fixed and std::setprecision persist and must be restored to avoid leaking into later writes. Setting setw once misses the fact that width resets after each insertion. Left alignment contradicts the right-alignment requirement, and the parser needs fixed columns, not inference. std::to_string and manual padding is workable but ignores the requirement to avoid leaking the formatting state of the stream, and the decimal precision would not be controlled by the stream.
-
15 Question 15 Single choice STL merge operations
Two sorted std::vector objects, one holding the current day's trade IDs and one holding yesterday's, must be combined into a single sorted sequence without duplicates in a new vector. The team wants the operation to use the standard merge machinery and avoid writing a manual two-pointer loop. Which call sequence is correct?
Correct Answer: CExplanationstd::set_union on two sorted ranges produces a sorted output containing each distinct element once, which is exactly the combined duplicate-free sequence required. merge followed by unique works only if duplicates are adjacent and the output keeps duplicates, so it is correct in effect but requires an extra pass; the requirement for standard machinery points to set_union as the single call. inplace_merge needs both halves in one container with a middle iterator and does not create a new vector. includes returns a bool and does not produce a merged sequence.
-
16 Question 16 Single choice Modifying STL algorithms
A graphics routine stores pixel colours in a std::list and must replace every occurrence of a specific colour with another, but the list is also referenced through iterators held by other threads that must stay valid. Which algorithm and container combination satisfies the requirement?
Correct Answer: DExplanationstd::replace only assigns new values to matching elements, so no element is removed or reallocated and iterators into a std::list remain valid. std::remove erases elements, which invalidates the iterators pointing to them, and the appended colour does not preserve position. Building a new list and swapping leaves the held iterators pointing at the old nodes, so they would refer to the wrong data. std::fill overwrites all elements, not only the matching ones.
-
17 Question 17 Dropdown STL Associative containers
A developer is writing a cache that maps a file path string to its last-modified timestamp. Lookups must be logarithmic in the number of entries and the keys must be iterated in sorted order for a report. Complete the declaration of the cache using the correct container template and key comparison behaviour.
Choose the correct value for each blank.
cache; where is used to store the map with std::string keys and iteration in sorted orderCorrect Answer:std::map cache; where std::map is used to store the map with std::string keys and iteration in sorted order
Explanationstd::map keeps keys in sorted order and provides logarithmic lookup, which matches both requirements. unordered_map is fast on average but does not iterate in sorted order. multimap permits duplicate keys, which a cache keyed by path should not have. std::set holds keys only and cannot store the timestamp value. The second blank confirms the container family, so std::map is the consistent answer.
-
18 Question 18 Single choice Templates
A numerics library provides a class template Vector with a fixed size N known at compile time. A maintainer adds a member function that multiplies the vector by a scalar and returns a new vector. Users report that code calling this function with Vector fails when the scalar is a double. Which change correctly addresses the root cause?
Correct Answer: CExplanationThe failure occurs because the member function forces the scalar to match T, so a double scalar cannot be applied to a Vector without a deduction-compatible signature. Making the scalar a separate template parameter lets the function accept any scalar and deduce the result type from the arithmetic. A macro sidesteps type safety and does not solve the deduction problem. Specialising the whole class for double is unrelated to the scalar argument. Turning N into a runtime value would discard the compile-time size guarantee and does not address the type mismatch.
These are 18 of the 228 questions in the full CPP pack.
Get All 228 QuestionsGet all 228 questions & answers
Full access options for C++ Institute CPP
Self-study
PDF Version
- 228 actual exam questions
- Compatible with all devices
- Printable PDF format
- No download limits
- 90 days free updates
- 24/7 customer support
Best value
Bundle Pack
- Discounted PDF + online access
- 228 actual exam questions
- Both PDF and online practice test
- Free 90 days updates
- No download or practice limits
- 24/7 customer support
Exam simulation
Online Practice Test
- 228 actual exam questions
- Actual exam environment
- 90 days free updates
- Browser-based software
- 24/7 customer support
100% Money Back Guarantee
Your success comes first
At DumpsProvider, we give you a 100% money back guarantee on all of our exam dumps. For us, your success is the #1 priority and we are more than confident that our exam material will help you pass the CPP Exam (CPP - C++ Certified Professional Programmer Exam) on your very first attempt.
In a rare case, if you fail your exam, we will refund your amount without asking a single question.