Limited-Time Offer: Enjoy 50% Savings! Coupon code: 50OFF Use it at checkout
Skip to content

Free C++ Institute CPP - C++ Certified Professional Programmer Exam Questions

Last updated: · 14 practice questions with answers and explanations

Page: 1 / 16 Total 228 questions

Want more questions? Get Premium Access.

Question 1

New Single answer

Topic: Templates

Skill tested: Applies function-template argument deduction and overload resolution to generic interfaces.

A telemetry library has a generic formatting function that accepts a value and returns a string. Most callers should use a template so that the function supports new numeric types without adding overloads. For `format(T value)`, the implementation streams `value` into an `std::ostringstream`. A caller passes a string literal, and the current template instantiation fails because the stream expression is ambiguous for the array type. The team wants to preserve the generic function and avoid changing all call sites. Which change best addresses the issue while keeping the function reusable?

Correct Answer: A. Add a non-template overload taking `const char*` that converts the text to `std::string` and delegates to the template.
Explanation:

A non-template overload for `const char*` handles string literals through the normal array-to-pointer conversion and can delegate using an `std::string`, avoiding the problematic array instantiation while retaining generic support for other types. Changing the parameter to `T&` can deduce an array reference rather than causing the desired conversion. `typename` and `class` are equivalent in this template-parameter context, and converting the interface to a class template does not solve the deduction or streaming issue.

Question 2

New Multiple answers

Topic: Templates

Skill tested: Diagnoses template instantiation errors involving dependent names and required disambiguation.

A numerical library defines a class template whose type parameter supplies a nested result type. The implementation includes `using result_type = T::result_type;` and later constructs a local object with `T::result_type value;`. Compilation fails only after the template is instantiated with a concrete matrix type. The team confirms that the matrix type does define `result_type`, and wants the smallest standard C++ correction without changing the public API. Which two edits resolve the dependent-name parsing problem? Select TWO.

Correct Answer: A. Write `typename T::result_type value;` for the local declaration.; D. Write `using result_type = typename T::result_type;`.
Explanation:

A qualified name that depends on a template parameter is not assumed to name a type during parsing. The `typename` keyword disambiguates both the alias target and the local declaration as types. The `template` disambiguator is used when a dependent qualified name is followed by a template-id, not to identify a dependent type. `auto` does not express the nested type in the alias, and adding another template parameter would alter the design rather than fix parsing.

Question 3

New Single answer

Topic: STL Sequential containers

Skill tested: Selects a sequential container based on insertion, traversal, and iterator-stability requirements.

A routing service maintains an ordered chain of active processing stages. It frequently inserts or removes stages at arbitrary positions using an iterator already held by the caller. It also traverses the entire chain in both directions, but rarely performs indexed access. Insertions and erasures must not invalidate iterators to other stages. The service does not require contiguous storage, and minimizing the cost of middle modifications matters more than cache locality. Which container is the best fit?

Correct Answer: B. `std::list`, because it supports bidirectional traversal and preserves other element iterators across insertion and erasure.
Explanation:

A doubly linked `std::list` supports bidirectional traversal and insertion or erasure at a known position without invalidating iterators to other elements. It does not provide random access, but the scenario explicitly says indexed access is rare and middle modification is important. `vector` and `deque` may invalidate iterators when elements are inserted or erased, with middle operations also requiring element movement. `array` has fixed size and cannot support the required dynamic stage changes.

Question 4

New Multiple answers

Topic: STL Sequential containers

Skill tested: Chooses sequence-container adapters for bounded operational access patterns.

An embedded controller has two independent work structures. One must process incoming commands in first-in, first-out order, and the other must always remove the command with the greatest priority value. Both structures need only insertion and removal at their prescribed ends; callers must not iterate through or access arbitrary elements. The implementation should use the standard library's adapter interfaces rather than expose a general-purpose sequence container. Which two adapters meet these requirements? Select TWO.

Correct Answer: D. `std::queue` for incoming commands.; E. `std::priority_queue` for greatest-priority commands.
Explanation:

`std::queue` presents FIFO operations through `front`, `back`, `push`, and `pop`, while `std::priority_queue` exposes the highest-priority element at its top and maintains the heap ordering as elements are added or removed. A stack is LIFO. A deque provides end operations but does not order elements by priority, and a list does not itself enforce FIFO access because callers can use other operations. The adapter interfaces match the requirement to restrict access.

Question 5

New Single answer

Topic: STL Associative containers

Skill tested: Chooses a map variant that preserves duplicate keys while supporting ordered lookup.

A compliance archive records every revision associated with a policy identifier. Several revisions may share the same identifier, and the system must iterate records in ascending identifier order. Analysts also need to retrieve the complete range of revisions for one identifier using standard associative-container operations. The values do not need to be unique, and replacing an earlier revision is not acceptable. Which container is most appropriate?

Correct Answer: C. `std::multimap`.
Explanation:

`std::multimap` stores multiple elements with equivalent keys and orders its elements according to the key comparator. `equal_range(id)` retrieves the full range associated with a policy identifier. A `map` allows only one element per key, and `operator[]` addresses that unique-key model rather than preserving every revision. An unordered map also permits only one value per key and does not provide sorted iteration. A set of pairs orders by both pair members and does not directly provide the requested keyed range lookup.

Question 6

New Multiple answers

Topic: STL Associative containers

Skill tested: Applies set uniqueness and comparator requirements when storing domain objects.

A build system must store unique package names in sorted order and reject a second package with a name already present. Package objects contain a name and a large mutable download-status field. Ordering must depend only on the package name; status changes must not alter the ordering relation while an object is stored. The team is considering a `std::set` and wants to avoid accidental equivalence rules based on the full object representation. Which two design decisions satisfy the requirements? Select TWO.

Correct Answer: A. Provide a strict weak ordering for `Package` that compares only package names.; C. Treat two packages as equivalent for set uniqueness when neither compares less than the other.
Explanation:

Associative containers use their comparator both to maintain ordering and to determine key equivalence: two values are equivalent when neither compares less than the other. Comparing only names therefore enforces uniqueness by package name, independent of status. Including mutable status in the ordering would make the ordering depend on a field that can change. Modifying a key in place can violate the tree's ordering invariants; remove and reinsert instead. A `multiset` permits equivalent keys rather than rejecting duplicates.

Question 7

New Single answer

Topic: Non-modifying STL algorithms

Skill tested: Uses `search` with compatible iterator ranges to locate a contiguous subsequence.

A log analyzer stores event codes in a `std::list` and receives a short signature as a `std::vector`. It must locate the first contiguous occurrence of the complete signature within the event list and report the starting iterator. The analyzer must not change either range, and it cannot assume random-access iterators for the list. Which standard algorithm is designed for this operation?

Correct Answer: A. `std::search`, called with the event range and signature range.
Explanation:

`std::search` finds the first occurrence of one sequence as a contiguous subsequence of another and works with forward iterators, which `std::list` supplies. It leaves both ranges unchanged and returns the starting iterator or the end iterator if no match exists. `find` searches for one value, not an entire pattern. `equal` compares ranges from their beginnings, and `binary_search` requires a sorted range and tests for a value rather than locating an arbitrary contiguous signature.

Question 8

New Single answer

Topic: Modifying STL algorithms

Skill tested: Applies erase-remove correctly to remove matching elements from a vector.

A monitoring application stores active sensor identifiers in a `std::vector`. During a maintenance sweep, it must remove every occurrence of a retired identifier while preserving the relative order of all remaining identifiers. The vector should retain its existing container type, and the application must not erase elements while iterating with invalidated iterators. Which approach is correct?

Correct Answer: C. Call `std::remove_if` with a predicate, then erase from the returned iterator to `end()`.
Explanation:

`std::remove_if` stably compacts elements that do not match the predicate and returns the new logical end, but it does not change the vector's size. Erasing the range from that iterator to the actual `end()` completes removal and preserves the relative order of retained elements. `remove` is also usable for a specific value but still requires the erase step; the stated predicate-based choice is the appropriate operation. `unique` removes only consecutive duplicates, while `partition` does not preserve order.

Question 9

New Multiple answers

Topic: Modifying STL algorithms

Skill tested: Selects algorithms that preserve or intentionally reorder elements during range transformation.

A report generator receives a mutable `std::vector` and must produce a second vector containing transformed numeric scores. The input records must remain unchanged, and the output must preserve their order. In a separate stage, it needs to rotate the input records so that the element at a selected middle iterator becomes first, without allocating another vector. Which two algorithm choices satisfy these requirements? Select TWO.

Correct Answer: C. Use `std::transform` with the input range and an output iterator into the second vector.; E. Use `std::rotate` on the input range with the selected middle iterator.
Explanation:

`std::transform` applies the score-producing operation to each input record and writes results to the destination range, leaving the source records unchanged and preserving element order. `std::rotate(first, middle, last)` rearranges the input in place so the element at `middle` becomes the first element, without requiring a second vector. `copy` does not perform the required projection, and reverse does not generally move an arbitrary middle element to the front. `remove_if` is for compaction based on a predicate, not rotation.

Question 10

New Single answer

Topic: Sorting STL operations

Skill tested: Uses binary-search algorithms only with ranges ordered by the same comparator.

A catalog team sorts a `std::vector` using a comparator that orders products by ascending SKU. A later lookup routine must find the range of products whose SKU equals a requested value, including all comparator-equivalent products. The vector remains unchanged between sorting and lookup. Which operation should the routine use?

Correct Answer: A. Call `std::equal_range` with the same SKU comparator used for sorting.
Explanation:

`std::equal_range` returns the subrange of elements equivalent to the requested value in a range partitioned according to the supplied ordering. Using the same SKU comparator as the sort is essential; a different comparator does not guarantee the precondition and can produce invalid results. A linear `find` does not identify the full equivalent range, and the stopping condition described does not define a general search. Sorting with an unrelated default ordering would discard the ordering needed for SKU lookup.

Question 11

New Single answer

Topic: STL merge operations

Skill tested: Merges sorted input ranges while preserving their ordering and retaining duplicate elements.

A billing service receives two independently generated `std::vector` ranges. Each range is already sorted by ascending account number using the same comparator. Charges with the same account number must remain separate, and the service needs one sorted output range without modifying either input. Which algorithm is the best choice?

Correct Answer: A. `std::merge`, writing to a destination with capacity for both ranges.
Explanation:

`std::merge` combines two sorted input ranges into a sorted output range and preserves multiplicities, so every charge remains represented. The output must have room for the total number of input elements, and the same ordering must be used for both inputs and the merge. `set_union` treats ranges as sorted sets and outputs the maximum multiplicity of equivalent values, potentially discarding duplicates present in both inputs. `inplace_merge` operates on adjacent sorted subranges within one range, while `includes` only tests containment.

Question 12

New Single answer

Topic: STL utilities and functional library

Skill tested: Uses standard function objects and binders to adapt predicates for algorithm calls.

A legacy C++ application uses standard algorithms and needs to count values greater than a runtime threshold. Its compiler supports the traditional standard functional library but the project cannot use lambdas or define a custom predicate type. The range contains integers, and the threshold is stored in `limit`. Which expression correctly adapts a standard comparison function object for `count_if`?

Correct Answer: C. `std::count_if(first, last, std::bind2nd(std::greater(), limit))`
Explanation:

In the traditional functional library, `std::bind2nd` binds the second argument of a binary function object. Applied to `std::greater`, the predicate becomes `greater(element, limit)`, which is true when the element exceeds the threshold. `bind1st` instead evaluates `greater(limit, element)`, reversing the comparison. `greater` is not constructed with a bound value, and `plus` produces a value rather than the required Boolean predicate. These legacy adapters are deprecated in later standards, but fit the stated environment.

Question 13

New Multiple answers

Topic: STL utilities and functional library

Skill tested: Selects standard utility operations for ordering and comparison of values.

A scheduling component maintains pairs of candidate completion times and needs reusable standard-library operations. For one calculation it must obtain the smaller of two values; for another it must compare a sequence using an equality predicate; and its sort comparator must order records by a member value. The implementation uses the classic STL utility and functional facilities and should not introduce a custom utility function for the first operation. Which two statements are correct? Select TWO.

Correct Answer: A. `std::min(a, b)` returns the lesser value according to the applicable ordering.; C. A binary predicate supplied to `std::equal` determines whether corresponding elements compare equal.
Explanation:

`std::min` selects the lesser of its arguments according to the ordering used, making it suitable for the stated two-value calculation. The predicate overload of `std::equal` uses the supplied binary predicate to compare corresponding elements; it does not reorder either range. `std::less` uses the record type's ordering operation and does not infer a member field, so a member-aware comparator is needed. `std::swap` is not restricted to container elements; it swaps compatible objects.

Question 14

New Single answer

Topic: STL advanced I/O

Skill tested: Configures stream formatting flags and precision without changing numeric values.

A financial reporting tool writes measurements to an `std::ostringstream`. Each value must appear in fixed-point notation with exactly three digits after the decimal point. The values must remain numeric internally, and the formatting should be set on the stream rather than implemented by manual string manipulation. Which statement sequence meets the output requirement?

Correct Answer: B. Apply `std::fixed` and `std::setprecision(3)` to the stream before inserting the values.
Explanation:

For floating-point output, `std::fixed` selects fixed-point notation, and `std::setprecision(3)` then specifies three digits after the decimal point. Without `fixed`, precision normally controls significant digits, so `setprecision(3)` alone does not guarantee three fractional digits. `scientific` produces exponent notation, contrary to the fixed-point requirement. `setw` sets a minimum field width for the next formatted value and does not control the number of decimal places.