STL Quiz - Languages C++
Free practice quiz: STL (Languages C++). 53 multiple-choice questions with answers and explanations. Play online, no sign-up needed.
Play all 53 questions freeSample questions
Which STL container provides constant time complexity for insertion and deletion at both ends?
- std::vector
- std::list
- std::deque
- std::set
Show answer
Answer: C. std::deque
std::deque (double-ended queue) offers constant time complexity O(1) for insertions and deletions at both the front and back, unlike std::vector which has amortized constant time for insertions/deletions at the back but linear time at the front. std::list has constant time for insertions/deletions anywhere, but accessing elements is linear. std::set has logarithmic time complexity for these operations.
What is an iterator in the context of STL?
- A variable that stores a value
- A pointer-like object that allows traversal and access to elements of a container
- A function that performs an operation on a container
- A data structure that stores key-value pairs
Show answer
Answer: B. A pointer-like object that allows traversal and access to elements of a container
Iterators are objects that act like pointers to elements within STL containers. They provide a standardized way to access elements, move through containers, and are fundamental to STL algorithms.
Which algorithm can be used to remove all occurrences of a specific value from a container like `std::vector`?
- std::erase
- std::remove
- std::pop_back
- std::delete
Show answer
Answer: B. std::remove
`std::remove` shifts all elements *not* equal to the specified value to the beginning of the range and returns an iterator to the new logical end. It does not actually change the size of the container. To remove the elements, you typically use the container's `erase` method with the iterator returned by `std::remove`. `std::erase` is a member function for some containers, or a free function since C++20 for sequence containers, that directly removes elements. `std::pop_back` removes the last element.
Which algorithm can be used to count the number of elements in a range that satisfy a specific condition?
- std::count
- std::find_if
- std::count_if
- std::accumulate
Show answer
Answer: C. std::count_if
`std::count_if` counts the number of elements in the range `[first, last)` for which the given predicate returns `true`. `std::count` counts occurrences of a specific value. `std::find_if` finds the first element satisfying a condition. `std::accumulate` sums elements.
What is the time complexity of accessing the last element of a `std::vector` using `v.back()`?
- O(1)
- O(log n)
- O(n)
- Amortized O(1)
Show answer
Answer: A. O(1)
Accessing the last element of a `std::vector` using `v.back()` is a constant time operation, O(1), because the vector stores its elements contiguously and knows the location of the last element.