CPP File Handling & Standard Template Library (STL) 2 — Questions and Answers
Question 1: Which STL container provides O(1) average-case insertion, deletion, and lookup?
- std::map
- std::unordered_map (Correct answer)
- std::multimap
- std::set
Correct answer: std::unordered_map
std::unordered_map uses a hash table internally, giving O(1) average-case for these operations.
Question 2: What does std::ifstream::seekg() do?
- Sets the put pointer position
- Sets the get pointer position (Correct answer)
- Flushes the input buffer
- Closes the file stream
Correct answer: Sets the get pointer position
seekg() repositions the get (read) pointer within an input stream.
Question 3: Which STL algorithm removes duplicate consecutive elements from a range?
- std::remove
- std::unique (Correct answer)
- std::sort
- std::partition
Correct answer: std::unique
std::unique collapses consecutive duplicates to single elements and returns an iterator to the new end.
Question 4: What is the return type of std::vector::emplace_back() in C++17?
- void
- iterator
- reference (Correct answer)
- bool
Correct answer: reference
In C++17, emplace_back() was changed to return a reference to the inserted element.
Question 5: Which file open mode flag creates a new file and truncates it if it already exists?
- std::ios::app
- std::ios::ate
- std::ios::trunc (Correct answer)
- std::ios::in
Correct answer: std::ios::trunc
std::ios::trunc discards any existing content when the file is opened.
Question 6: What does std::deque offer compared to std::vector?
- Faster random access
- O(1) push_front and push_back (Correct answer)
- Less memory overhead
- Cache-friendly contiguous storage
Correct answer: O(1) push_front and push_back
std::deque supports efficient O(1) insertion and deletion at both the front and back.
Question 7: Which function template in <algorithm> reorders elements so those satisfying a predicate come first?
- std::sort_if
- std::stable_sort
- std::partition (Correct answer)
- std::nth_element
Correct answer: std::partition
std::partition reorders a range so elements satisfying the predicate precede those that don't.
Which STL container provides O(1) average-case insertion, deletion, and lookup?