C++ CPP study materials
C++ CPP study resources

C++ CPP practice questions

One question at a time. Build your C++ CPP understanding.

First 50 of 190 questions. Each one lists the choices, the correct answer, and an explanation. The checker at the top of this page saves progress in this browser when it is available.

Continue in the practice tool above to load more questions, 50 at a time.

Question 1C++ standard containers, iterators and algorithm contracts

Which STL sequence container provides constant-time random access AND amortized constant-time push_back, but only linear-time insertion in the middle?

  1. std::vector Correct answer.
  2. std::list
  3. std::forward_list
  4. std::set

Explanation

std::vector stores elements in a contiguous block, giving O(1) random access via operator[] and amortized O(1) push_back due to geometric reallocation. Insertion in the middle is O(n) because elements after the insertion point must shift. std::list gives O(1) middle insertion but no random access; std::set is associative, not sequential.

Question 2C++ standard containers, iterators and algorithm contracts

Given std::vector<int> v = {1,2,3,4,5}; v.erase(v.begin() + 2); what does v contain afterwards?

  1. {1, 2, 4, 5} Correct answer.
  2. {1, 2, 3, 5}
  3. {1, 2, 3, 4, 5}
  4. {2, 3, 4, 5}

Explanation

v.begin() + 2 points at the element with value 3 (index 2). erase removes that element and shifts the tail left, so the vector becomes {1, 2, 4, 5}. erase returns an iterator to the new position of the element that followed the erased one (here, the 4).

Question 3C++ standard containers, iterators and algorithm contracts

What is the time complexity of inserting at the front of a std::deque?

  1. O(n)
  2. Amortized O(1) Correct answer.
  3. O(log n)
  4. O(n^2)

Explanation

std::deque is implemented as a sequence of fixed-size blocks indexed by a map (an array of block pointers). push_front allocates a new block at the front when needed; on average it is amortized O(1). std::vector, by contrast, has O(n) front insertion because every element must shift.

Question 4C++ standard containers, iterators and algorithm contracts

Which listed option identifies the unusual packed-bit/proxy-reference behavior of std::vector<bool>, rather than claiming it behaves identically to an ordinary vector of independently addressable bool objects?

  1. It is a specialization that packs bits, so its iterator does NOT yield true bool& references and it does not satisfy Container requirements fully Correct answer.
  2. It does not exist - only std::vector<int> exists
  3. It is deprecated and removed in C++17
  4. It only supports push_back, not insert

Explanation

The relevant property in the keyed option is proxy access rather than an ordinary bool reference for each independently addressable element. vector<bool> is a supported specialized container, not universally wrong or removed. Its exact generic-algorithm compatibility must follow the relevant standard/version requirements, not a blanket judgment that all uses are invalid.

Question 5C++ standard containers, iterators and algorithm contracts

For the usual merge-sort-based std::list::sort implementation, which listed description explains why a list uses its supported sorting member rather than passing its iterators to std::sort?

  1. std::list::sort is faster than std::sort on contiguous data
  2. std::sort needs random-access iterators; list iterators are bidirectional, so std::list provides its own merge sort Correct answer.
  3. std::sort can only sort vectors
  4. std::list::sort is deprecated and should be replaced with std::sort

Explanation

A list’s iterators are bidirectional, whereas std::sort requires random-access iterators. The member operation supports sorting that container under its actual contract; merge sort is a common implementation approach, not a universally mandated internal algorithm. Stable ordering and complexity follow the relevant member contract.

Question 6C++ standard containers, iterators and algorithm contracts

Comparing splice of an entire std::list with splice of a proper subrange between two distinct lists, which listed complexity description matches the usual standard contract?

  1. Always O(n)
  2. O(1) when transferring an entire list, O(n) when transferring a sub-range with size unknown Correct answer.
  3. Always O(1)
  4. O(log n)

Explanation

Moving an entire list has constant complexity under the relevant equal-allocator preconditions. Moving a proper range between distinct lists has linear complexity in the range length, while same-list range operations have different complexity. The keyed phrase describes the cross-list case supplied here, not every splice overload.

Question 7C++ standard containers, iterators and algorithm contracts

What does this code print? #include <iostream> #include <vector> int main() { std::vector<int> v; for (int i = 0; i < 5; ++i) v.emplace_back(i * i); for (int x : v) std::cout << x << ' '; }

  1. Compilation error
  2. 1 4 9 16 25
  3. 0 1 2 3 4
  4. 0 1 4 9 16 Correct answer.

Explanation

emplace_back constructs the element in place using the supplied arguments. Each iteration appends i*i for i in 0..4: 0, 1, 4, 9, 16. emplace_back differs from push_back by avoiding a temporary when constructing in place, but for trivial types like int the difference is negligible.

Question 8C++ standard containers, iterators and algorithm contracts

What is the iterator category of std::list<T>::iterator?

  1. Forward iterator
  2. Random-access iterator
  3. Bidirectional iterator Correct answer.
  4. Input iterator

Explanation

std::list is a doubly linked list, so its iterator can move forward and backward (++it and --it) but does not support random access (it + n in O(1) is not guaranteed). That makes it a bidirectional iterator. std::vector and std::deque iterators are random-access; std::forward_list iterators are only forward.

Question 9C++ standard containers, iterators and algorithm contracts

Which iterator category is required by std::find?

  1. Input iterator (single-pass forward) Correct answer.
  2. Random-access iterator
  3. Bidirectional iterator
  4. Output iterator

Explanation

std::find only needs to compare each element to the target and advance one step at a time, so it accepts any iterator that satisfies the InputIterator requirements. That makes it usable with any container - even std::istream_iterator. Random-access is required by std::sort and std::nth_element, not std::find.

Question 10C++ standard containers, iterators and algorithm contracts

Which listed resizable container supports ordinary element insertion without invalidating iterators to its existing elements?

  1. std::deque
  2. std::vector
  3. std::list Correct answer.
  4. std::array

Explanation

std::list inserts/removes elements without affecting iterators to other elements (each node is independently allocated). std::vector invalidates iterators on reallocation (and any insertion past the inserted point). std::deque invalidates ALL iterators on insert/erase except at front/back, even for valid subscripts. std::array is fixed-size and has no insert.

Question 11C++ standard containers, iterators and algorithm contracts

What does std::back_inserter return?

  1. An iterator pointing to the last element of the container
  2. A reverse iterator over the container
  3. An output iterator that calls push_back on the supplied container for each assignment Correct answer.
  4. A const iterator suitable for read-only iteration

Explanation

std::back_inserter(c) wraps a container in a back_insert_iterator. Algorithms like std::copy and std::transform that write through the iterator end up calling c.push_back. This avoids preallocating the destination - the container grows as elements are produced.

Question 12C++ standard containers, iterators and algorithm contracts

What is the iterator category of std::istream_iterator<int>?

  1. Bidirectional iterator
  2. Forward iterator
  3. Input iterator (single-pass) Correct answer.
  4. Random-access iterator

Explanation

istream_iterator reads values from a stream as they are extracted. Once advanced past a value, you cannot revisit it - that is the defining property of an input iterator. ostream_iterator is similarly an output iterator. Algorithms requiring forward+ iterators (like std::sort) cannot operate directly on istream_iterator.

Question 13C++ standard containers, iterators and algorithm contracts

Given std::vector<int> v = {1, 2, 3}; what is the result of *(v.rbegin())?

  1. Undefined behavior
  2. 1
  3. 2
  4. 3 Correct answer.

Explanation

rbegin returns a reverse_iterator that conceptually points 'one past' the logical end and dereferences to the LAST element. So *v.rbegin() yields 3. rend points 'one before' begin and is the past-the-end sentinel for reverse iteration.

Question 14C++ standard containers, iterators and algorithm contracts

What is the output of std::distance(v.begin(), v.end()) for std::vector<int> v(7)?

  1. 0
  2. 7 Correct answer.
  3. Undefined
  4. 6

Explanation

std::distance returns the number of increments needed to go from first to last. For a 7-element vector, that is 7. On random-access iterators it is O(1) (just last - first); for others it is O(n).

Question 15C++ standard containers, iterators and algorithm contracts

For the supplied representative introsort-based implementation of std::sort, which listed reason explains its need for a random-access iterator range?

  1. It needs to call .size() on the underlying container
  2. Internally it uses introsort, which needs constant-time arbitrary jumps for partitioning Correct answer.
  3. Random-access iterators are the only ones that support operator==
  4. Random-access iterators avoid copying elements during a swap

Explanation

The supplied introsort example uses constant-time arbitrary iterator jumps during its work, matching the keyed description. Independently, std::sort requires random-access iterators by contract. The C++ standard does not universally mandate introsort as the internal implementation; compare requirements rather than assume one library’s code defines the standard.

Question 16C++ standard containers, iterators and algorithm contracts

What does this code print? #include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> v = {3, 1, 4, 1, 5, 9, 2, 6}; std::sort(v.begin(), v.end()); for (int x : v) std::cout << x; }

  1. 11234569 Correct answer.
  2. 12345699
  3. 31415926
  4. 96543211

Explanation

std::sort sorts the vector in ascending order by default. The sorted sequence is 1,1,2,3,4,5,6,9 - printing without separators yields 11234569.

Question 17C++ standard containers, iterators and algorithm contracts

What does the erase-remove idiom achieve?

  1. Sorts the container while removing duplicates
  2. Forces the compiler to skip iterator invalidation checks
  3. Removes only the first matching element from a container
  4. Logically removes matching elements with std::remove and then physically erases them from the container Correct answer.

Explanation

std::remove (and remove_if) shift non-matching elements to the front and return an iterator to the new logical end, but do NOT change container size - the tail still holds unspecified values. To truly shrink the container you must call container.erase(remove(...), container.end()). This is the erase-remove idiom.

Question 18C++ standard containers, iterators and algorithm contracts

What does this code print? #include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> v = {1, 2, 3, 2, 4, 2, 5}; auto it = std::remove(v.begin(), v.end(), 2); std::cout << v.size() << ' ' << (it - v.begin()); }

  1. 7 4 Correct answer.
  2. 4 4
  3. 7 7
  4. 4 7

Explanation

std::remove does NOT shrink the container - v.size() remains 7. It returns an iterator to the new logical end, which is at offset 4 (the four non-2 elements 1, 3, 4, 5 are at indices 0..3). The tail v[4]..v[6] now holds unspecified values.

Question 19C++ standard containers, iterators and algorithm contracts

What does this code print? #include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> v = {1, 2, 3, 4, 5}; auto it = std::find(v.begin(), v.end(), 3); std::cout << *it << ' ' << (it - v.begin()); }

  1. 3 2 Correct answer.
  2. 3 3
  3. 2 3
  4. End iterator dereferenced

Explanation

std::find returns an iterator to the first element equal to 3, which is at index 2 (zero-based). Dereferencing prints 3, and (it - v.begin()) yields 2. find returns end() only when no match is found.

Question 20C++ standard containers, iterators and algorithm contracts

Which header declares std::sort, std::find, std::transform, and std::copy?

  1. <numeric>
  2. <algorithm> Correct answer.
  3. <utility>
  4. <functional>

Explanation

Standard non-numeric algorithms live in <algorithm>. <numeric> holds accumulate, inner_product, partial_sum, iota, reduce. <utility> has pair, move, swap (pre-C++11). <functional> holds function objects, std::function, bind.

Question 21C++ standard containers, iterators and algorithm contracts

What does this code print? #include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> v = {1, 2, 3, 4}; std::vector<int> w(v.size()); std::transform(v.begin(), v.end(), w.begin(), [](int x){ return x * x; }); for (int x : w) std::cout << x << ' '; }

  1. 0 0 0 0
  2. 1 2 3 4
  3. 2 4 6 8
  4. 1 4 9 16 Correct answer.

Explanation

std::transform applies the unary lambda to each element of v and writes the result into w. The squares of 1, 2, 3, 4 are 1, 4, 9, 16. The destination w must already have enough space (or use std::back_inserter); here w is sized to v.size().

Question 22C++ standard containers, iterators and algorithm contracts

What does this code print? #include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> v = {1, 2, 3, 4, 5}; int n = std::count_if(v.begin(), v.end(), [](int x){ return x % 2 == 0; }); std::cout << n; }

  1. 5
  2. 3
  3. 2 Correct answer.
  4. 0

Explanation

count_if counts elements satisfying the predicate. Even numbers in {1,2,3,4,5} are 2 and 4 - that is 2 elements.

Question 23C++ standard containers, iterators and algorithm contracts

What does this code print? #include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> v = {1, 2, 3, 4, 5, 6}; auto it = std::partition(v.begin(), v.end(), [](int x){ return x % 2 == 0; }); std::cout << (it - v.begin()); }

  1. 3 Correct answer.
  2. 0
  3. 6
  4. 2

Explanation

std::partition rearranges elements so all predicate-true elements come first; it returns an iterator to the first false element. There are 3 even numbers (2, 4, 6), so the partition point is at offset 3. The relative order within each half is unspecified - use std::stable_partition to preserve order.

Question 24C++ standard containers, iterators and algorithm contracts

What does std::stable_sort guarantee that std::sort does not?

  1. Equivalent elements retain their original relative order Correct answer.
  2. O(n log n) worst-case complexity
  3. In-place sorting with no extra memory
  4. Only one comparison per element pair

Explanation

stable_sort preserves the relative order of equivalent elements. std::sort gives O(n log n) on average but is NOT stable. The trade-off: stable_sort typically allocates extra memory for a merge-sort buffer; std::sort is in-place. Both have the same worst-case time complexity guarantee since C++11.

Question 25C++ standard containers, iterators and algorithm contracts

What does this code print? #include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> v = {3, 1, 4, 1, 5, 9, 2, 6}; std::nth_element(v.begin(), v.begin() + 3, v.end()); std::cout << v[3]; }

  1. 9
  2. 1
  3. 3 Correct answer.
  4. Implementation-defined

Explanation

std::nth_element places at position v.begin() + 3 the element that would be there if the range were fully sorted, partitioning the rest so smaller elements come before and larger after. Sorted, {1,1,2,3,4,5,6,9} has the 4th element (index 3) equal to 3. The other partitions are unordered - only v[3] is guaranteed.

Question 26C++ standard containers, iterators and algorithm contracts

What does this code print? #include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> v = {1, 2, 3}; std::vector<int> w = {4, 5, 6}; std::vector<int> r(6); std::merge(v.begin(), v.end(), w.begin(), w.end(), r.begin()); for (int x : r) std::cout << x; }

  1. 142536
  2. 654321
  3. 123456 Correct answer.
  4. 111222

Explanation

std::merge requires both input ranges to be sorted by the comparator. It interleaves them into the output to produce a single sorted sequence. {1,2,3} merged with {4,5,6} yields {1,2,3,4,5,6}. The destination must have at least N1+N2 elements (here r has size 6).

Question 27C++ standard containers, iterators and algorithm contracts

What does this code print? #include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> v = {1, 2, 3, 4, 5}; std::reverse(v.begin(), v.end()); for (int x : v) std::cout << x; }

  1. 54321 Correct answer.
  2. 12345
  3. 15432
  4. Empty

Explanation

std::reverse reverses elements in place across the iterator range. It requires bidirectional iterators (so std::list works) and runs in O(n/2) swaps. {1,2,3,4,5} becomes {5,4,3,2,1}.

Question 28C++ standard containers, iterators and algorithm contracts

What does this code print? #include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> v = {1, 2, 3, 4, 5}; std::rotate(v.begin(), v.begin() + 2, v.end()); for (int x : v) std::cout << x; }

  1. 12345
  2. 21354
  3. 54321
  4. 34512 Correct answer.

Explanation

std::rotate(first, middle, last) makes 'middle' the new first element, with elements before middle moved to the end (preserving relative order). Original {1,2,3,4,5} with middle = begin+2 (the 3) becomes {3,4,5,1,2}.

Question 29C++ standard containers, iterators and algorithm contracts

What does this code print? #include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> v = {1, 1, 2, 2, 3, 3, 3, 4}; auto it = std::unique(v.begin(), v.end()); v.erase(it, v.end()); for (int x : v) std::cout << x; }

  1. 1111
  2. 11223334
  3. 1234 Correct answer.
  4. 1233

Explanation

std::unique removes CONSECUTIVE duplicates by shifting unique values forward and returning a new logical end. Combined with erase to truly shrink the container, the {1,1,2,2,3,3,3,4} input becomes {1,2,3,4}. Note: unique only removes consecutive dups - sort first if you want full deduplication.

Question 30C++ standard containers, iterators and algorithm contracts

What does this code print? #include <iostream> #include <vector> #include <algorithm> #include <iterator> int main() { std::vector<int> v = {1, 2, 3, 4, 5}; std::copy_if(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " "), [](int x){ return x > 2; }); }

  1. 1 2
  2. 3 4 5 Correct answer.
  3. 1 2 3 4 5
  4. Compilation error

Explanation

std::copy_if writes only elements satisfying the predicate. Combined with std::ostream_iterator<int>(std::cout, ' '), it streams 3, 4, 5 (each followed by a space). ostream_iterator is an output iterator that writes to a stream on each assignment.

Question 31C++ standard containers, iterators and algorithm contracts

What does this code print? #include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> v = {5, 3, 8, 1, 9}; std::cout << *std::min_element(v.begin(), v.end()) << ' ' << *std::max_element(v.begin(), v.end()); }

  1. 1 9 Correct answer.
  2. 5 9
  3. 9 1
  4. 1 5

Explanation

min_element and max_element each return iterators to the smallest and largest elements respectively. Dereferencing yields 1 and 9. Both run in O(n). Use std::minmax_element to get both in a single pass with at most 3n/2 comparisons.

Question 32C++ standard containers, iterators and algorithm contracts

What does this code print? #include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> v = {1, 2, 3}; std::vector<int> w = {1, 2, 3}; std::cout << std::equal(v.begin(), v.end(), w.begin()); }

  1. true
  2. 0
  3. 1 Correct answer.
  4. Compilation error

Explanation

std::equal returns true if every element of the first range equals the corresponding element of the second. Since both vectors hold {1,2,3}, the result is true, which prints as 1 (default bool formatting). Add std::boolalpha to print 'true'.

Question 33C++ standard containers, iterators and algorithm contracts

What does this code print? #include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> v = {1, 2, 3, 4, 5}; bool any = std::any_of(v.begin(), v.end(), [](int x){ return x > 4; }); bool all = std::all_of(v.begin(), v.end(), [](int x){ return x > 0; }); std::cout << any << all; }

  1. 10
  2. 11 Correct answer.
  3. 01
  4. 00

Explanation

any_of returns true if AT LEAST one element matches the predicate (5 > 4 is true). all_of returns true only if EVERY element matches (every value is > 0). Both are true, printed as 1 each.

Question 34C++ standard containers, iterators and algorithm contracts

What does this code print? #include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> v = {1, 2, 3, 4, 5}; std::for_each(v.begin(), v.end(), [](int& x){ x *= 2; }); for (int x : v) std::cout << x << ' '; }

  1. 1 4 9 16 25
  2. 1 2 3 4 5
  3. 2 4 6 8 10 Correct answer.
  4. Empty

Explanation

std::for_each applies the supplied function/lambda to each element. The lambda takes int& by reference, so the doubling mutates the original vector. After the call, each element is twice its original value.

Question 35C++ standard containers, iterators and algorithm contracts

What does this code print? #include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> v = {1, 2, 3}; auto comp = [](int a, int b){ return a > b; }; std::sort(v.begin(), v.end(), comp); for (int x : v) std::cout << x; }

  1. 132
  2. 123
  3. 321 Correct answer.
  4. 213

Explanation

Passing a comparator that returns a > b to std::sort means 'a should come before b if a is greater', producing descending order. {1,2,3} sorts to {3,2,1}.

Question 36C++ standard containers, iterators and algorithm contracts

What does this code print? #include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> v = {5, 1, 4, 2, 8}; std::partial_sort(v.begin(), v.begin() + 3, v.end()); std::cout << v[0] << v[1] << v[2]; }

  1. 125
  2. 124 Correct answer.
  3. 148
  4. 543

Explanation

partial_sort(first, middle, last) sorts the smallest (middle - first) elements into [first, middle) in ascending order; elements after middle are unspecified. The 3 smallest of {5,1,4,2,8} are {1,2,4}, placed at indices 0, 1, 2.

Question 37C++ standard containers, iterators and algorithm contracts

What does this code print? #include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> v = {1, 2, 3, 4, 5}; std::vector<int> w(5); std::reverse_copy(v.begin(), v.end(), w.begin()); for (int x : w) std::cout << x; }

  1. Empty
  2. 12345
  3. 00000
  4. 54321 Correct answer.

Explanation

reverse_copy writes elements from the source range into the destination in reverse order, leaving the source untouched. v stays as {1,2,3,4,5}; w receives {5,4,3,2,1}.

Question 38C++ standard containers, iterators and algorithm contracts

What does this code print? #include <iostream> #include <iterator> #include <vector> #include <algorithm> int main() { std::vector<int> v = {1, 2, 3, 4, 5, 6}; std::vector<int> w = {2, 4}; std::vector<int> diff; std::set_difference(v.begin(), v.end(), w.begin(), w.end(), std::back_inserter(diff)); for (int x : diff) std::cout << x; }

  1. 123456
  2. 246
  3. 1356 Correct answer.
  4. 0

Explanation

set_difference produces elements present in the first sorted range but NOT the second. From {1,2,3,4,5,6} minus {2,4}, the result is {1,3,5,6}. Both inputs must be sorted by the same comparator.

Question 39C++ standard containers, iterators and algorithm contracts

What does std::generate(v.begin(), v.end(), [n=0]() mutable { return n++; }); do?

  1. Fills v with copies of 0
  2. Fills v with 0, 1, 2, ... ascending values starting from 0 Correct answer.
  3. Fills v with 1, 2, 3, ... starting from 1
  4. Compilation error

Explanation

std::generate calls the supplied nullary functor for each element and assigns the result. The lambda uses C++14 init-capture (n=0) and post-increment, so it returns 0, 1, 2, .... Equivalent behaviour is achievable with std::iota(v.begin(), v.end(), 0).

Question 40C++ standard containers, iterators and algorithm contracts

What does this code print? #include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> v = {1, 2, 3}; auto [it1, it2] = std::mismatch(v.begin(), v.end(), v.begin()); std::cout << (it1 == v.end()) << (it2 == v.end()); }

  1. 10
  2. 11 Correct answer.
  3. 01
  4. 00

Explanation

std::mismatch compares two ranges and returns a pair of iterators to the first position where they differ. Comparing v with itself, no mismatch is found - both iterators advance to v.end(). Both equality checks are true (printed as 1).

Question 41C++ standard containers, iterators and algorithm contracts

What does this code print? #include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> v = {1, 2, 3, 4, 5}; auto it = std::find_if_not(v.begin(), v.end(), [](int x){ return x < 4; }); std::cout << *it; }

  1. End iterator dereferenced
  2. 5
  3. 1
  4. 4 Correct answer.

Explanation

find_if_not returns an iterator to the first element for which the predicate is FALSE. Predicate is x < 4; the first element where that fails is 4 (since 4 < 4 is false). Dereferencing yields 4.

Question 42C++ standard containers, iterators and algorithm contracts

What does this code print? #include <iostream> #include <vector> #include <algorithm> #include <iterator> int main() { std::vector<int> v = {3, 1, 4, 1, 5}; std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, "")); }

  1. 13145
  2. 3 1 4 1 5
  3. 31415 Correct answer.
  4. Empty

Explanation

std::copy writes each element through the output iterator. ostream_iterator<int> with an empty separator string writes each int directly with no delimiter. The result is the digits concatenated: '31415'.

Question 43C++ standard containers, iterators and algorithm contracts

What does this code print? #include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> v = {1, 2, 3, 4}; std::vector<int> w = {1, 2, 3, 4}; bool eq = std::lexicographical_compare(v.begin(), v.end(), w.begin(), w.end()); std::cout << eq; }

  1. 0 Correct answer.
  2. 1
  3. true
  4. false

Explanation

lexicographical_compare returns true if the first range is STRICTLY LESS than the second. Equal ranges are NOT strictly less, so the result is false (printed as 0). For equality, use std::equal instead. For ordering operator (==, <, etc.) on containers, the relational operators of the container implement this.

Question 44C++ standard containers, iterators and algorithm contracts

What is the result of std::is_sorted(v.begin(), v.end()) on v = {1, 2, 2, 3}?

  1. true (1) Correct answer.
  2. false (0)
  3. Implementation-defined
  4. Compilation error

Explanation

std::is_sorted returns true if the range is sorted by std::less (or the supplied comparator). Equivalent elements are allowed because the relation is non-strict - adjacent pairs need !(b < a). {1,2,2,3} satisfies that, so is_sorted is true.

Question 45C++ standard containers, iterators and algorithm contracts

What is the time complexity of std::map<Key, Value>::find?

  1. O(1)
  2. O(log n) Correct answer.
  3. O(n)
  4. O(n log n)

Explanation

std::map is implemented as a balanced binary search tree (typically a red-black tree), so find walks log n levels to locate a key. std::unordered_map is the hash-based associative container that gives average O(1) lookup but worst-case O(n).

Question 46C++ standard containers, iterators and algorithm contracts

What does this code print? #include <iostream> #include <set> int main() { std::set<int> s = {5, 3, 8, 1, 5, 3}; for (int x : s) std::cout << x << ' '; }

  1. 1 3 5 8 Correct answer.
  2. 5 3 8 1 5 3
  3. 1 3 3 5 5 8
  4. 8 5 3 1

Explanation

std::set stores unique keys in sorted order (ascending by default). Duplicates 5 and 3 are collapsed, so the set contains {1, 3, 5, 8}. Iteration is in-order traversal, yielding ascending output.

Question 47C++ standard containers, iterators and algorithm contracts

What does this code print? #include <iostream> #include <map> int main() { std::map<std::string, int> m; m["a"] = 1; std::cout << m["b"]; }

  1. 0 Correct answer.
  2. 1
  3. Compilation error
  4. Undefined behavior

Explanation

std::map<K,V>::operator[] inserts a default-constructed value if the key is missing. For int, default construction yields zero (value-initialization). So m["b"] inserts the entry b -> 0 and returns that 0. This is a common gotcha - use map::find or map::at when you want lookup without insertion.

Question 48C++ standard containers, iterators and algorithm contracts

How does std::map::at differ from std::map::operator[]?

  1. at is faster because it skips bounds checking
  2. at throws std::out_of_range if the key is missing; operator[] inserts a default-constructed value Correct answer.
  3. at returns a copy while operator[] returns a reference
  4. at is only available on const maps

Explanation

map::at performs a checked lookup and throws std::out_of_range if the key is absent. operator[] silently inserts a default-constructed value for missing keys. Both return a reference, and both are available on non-const maps (at also has a const overload returning const reference).

Question 49C++ standard containers, iterators and algorithm contracts

What does this code print? #include <iostream> #include <string> #include <map> int main() { std::map<int, std::string> m = {{2, "b"}, {1, "a"}, {3, "c"}}; for (auto& [k, v] : m) std::cout << k << v; }

  1. 1a2b3c Correct answer.
  2. 2b1a3c
  3. 3c2b1a
  4. Compilation error

Explanation

std::map iterates in key order (ascending by default). Even though insertion order was 2,1,3, traversal yields keys 1, 2, 3. C++17 structured bindings unpack each std::pair<const int, std::string>. Output: 1a 2b 3c concatenated.

Question 50C++ standard containers, iterators and algorithm contracts

What is the time complexity of std::multiset<int>::erase(value)?

  1. O(log n + count(value)) - erases all matching elements Correct answer.
  2. O(log n) - erases just one matching element
  3. O(1)
  4. O(n)

Explanation

multiset::erase(key) erases ALL elements equivalent to key and returns the count. The cost is O(log n) to locate the equal_range plus linear in the number of erased elements. To erase only one element pass an iterator: ms.erase(ms.find(key)).