




































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
A technical coding-knowledge exam focused on advanced C++ concepts such as memory management, templates, OOP design, exception handling, STL libraries, multithreading, algorithms, and compiler behavior. Includes code-analysis questions, debugging tasks, and real-world application-scenario problems.
Typology: Exams
1 / 44
This page cannot be seen from the preview
Don't miss anything!





































Question 1. Which keyword is used to declare a function template? A) template B) typename C) class D) generic Answer: A Explanation: The template keyword introduces a template declaration, e.g., template. Question 2. In a function template, how are template arguments deduced when calling max(5, 3.2)? A) Both arguments are deduced as double B) Both arguments are deduced as int C) Compilation error – types differ D) The first argument’s type is used for both Answer: A Explanation: Template argument deduction performs conversions; the int 5 is converted to double, so T is deduced as double. Question 3. Which of the following statements correctly explicitly instantiates a class template Matrix for int? A) template class Matrix; B) template Matrix; C) explicit Matrix; D) instantiate Matrix; Answer: A Explanation: template class Matrix; forces the compiler to generate code for the int specialization. Question 4. What is the primary purpose of a total (explicit) specialization? A) To provide a generic fallback implementation B) To overload a function for different parameter counts C) To define a completely different implementation for a specific type D) To enable partial type deduction
Answer: C Explanation: An explicit specialization replaces the primary template for a particular set of template arguments. Question 5. Which syntax correctly defines a member function of a class template Stack outside the class definition? A) template void Stack::push(const T&); B) void Stack::push(const T&); C) template void Stack::push(const T&); D) template void Stack::push(const T&); Answer: A Explanation: The definition must repeat the template header and qualify the class with its template arguments. Question 6. Given template class Container> class Wrapper;, what is Container? A) A type alias B) A non-type template parameter C) A template-template parameter representing a class template that takes one type argument D) A function pointer Answer: C Explanation: template class Container denotes a template that itself takes a single type parameter. Question 7. Which statement about nested class templates is true? A) The inner template cannot depend on the outer template’s parameters. B) The outer template must be fully specialized before the inner can be used. C) The inner template can access the outer template’s type parameters. D) Nested templates are prohibited in the C++ standard. Answer: C
Explanation: Reallocation copies all existing elements (O(n)), but over many insertions the average cost is constant. Question 11. Which member function of std::deque provides constant-time access to the element at the front? A) front() B) back() C) at(0) D) operator[] Answer: A Explanation: front() returns a reference to the first element in constant time. Question 12. In a std::list, which operation has linear complexity? A) Inserting at the beginning B) Inserting after a known iterator C) Accessing the nth element with operator[] (which does not exist) D) Erasing a known iterator Answer: C (trick) Explanation: std::list does not provide random access; to reach the nth element you must traverse the list, which is O(n). Question 13. Which adapter is implemented on top of std::deque by default? A) std::stack B) std::queue C) std::priority_queue D) All of the above Answer: D Explanation: All three adapters default to using std::deque as the underlying container. Question 14. What does std::priority_queue::top() return? A) The smallest element (min-heap) B) The largest element (max-heap) by default C) The element inserted most recently
D) The element with the highest priority flag set by the user Answer: B Explanation: By default std::priority_queue uses std::less, creating a max-heap, so top() yields the greatest element. Question 15. Which iterator category supports the operator+ operation? A) Input iterator B) Forward iterator C) Bidirectional iterator D) Random-access iterator Answer: D Explanation: Only random-access iterators guarantee pointer arithmetic like it + n. Question 16. Which of the following is a valid declaration of a bidirectional iterator for a custom container? A) using iterator = std::input_iterator_tag; B) struct iterator { using iterator_category = std::bidirectional_iterator_tag; /* ... */ }; C) typedef std::bidirectional_iterator_tag iterator; D) std::iterator (deprecated but still valid) Answer: B Explanation: The iterator must expose a nested iterator_category type; option B does that. Question 17. What is the result of std::set s = {3,1,4,1,5}; s.size();? A) 5 B) 4 C) 3 D) Compilation error due to duplicate 1 Answer: B Explanation: std::set stores unique keys; the duplicate 1 is ignored, leaving {1,3,4,5}.
C) std::set, std::less<>> s; D) std::set> s; (default) Answer: A Explanation: Providing a functor with the desired comparison logic customizes the ordering. Question 22. Which algorithm returns true if a value exists in a sorted range without modifying the range? A) std::find B) std::binary_search C) std::lower_bound D) std::count Answer: B Explanation: binary_search works on sorted ranges and only inspects elements. Question 23. What does std::lower_bound(v.begin(), v.end(), 10) return? A) Iterator to the first element greater than 10 B) Iterator to the first element not less than 10 C) Iterator to the last element less than 10 D) Iterator to the element equal to 10, or v.end() if not found Answer: B Explanation: lower_bound yields the first position where value could be inserted without breaking order. Question 24. Which algorithm would you use to replace every occurrence of 5 with 0 in a std::vector? A) std::replace B) std::replace_if C) std::transform D) std::remove Answer: A Explanation: replace swaps all elements equal to a given old value with a new one.
Question 25. Which STL algorithm removes elements logically but does not change the container size? A) std::remove B) std::erase C) std::pop_back D) std::clear Answer: A Explanation: remove reorders elements and returns an iterator to the new logical end; the container must be resized (e.g., via erase). Question 26. After calling auto it = std::remove(v.begin(), v.end(), 3); v.erase(it, v.end());, what is the overall effect? A) Elements equal to 3 are erased from v. B) The vector is reversed. C) All elements are shifted left by one position. D) The vector size remains unchanged. Answer: A Explanation: The two-step idiom actually erases the unwanted elements. Question 27. Which algorithm copies elements from one range to another while applying a unary operation? A) std::copy B) std::transform C) std::generate D) std::fill Answer: B Explanation: transform applies a function to each source element and writes the result to the destination. Question 28. What is the difference between std::fill and std::fill_n? A) fill works on containers, fill_n works on raw arrays. B) fill fills a whole range, fill_n fills a specified count of elements. C) fill uses a value-type, fill_n uses a generator. D) No difference; they are synonyms. Answer: B
Question 32. Which algorithm guarantees stable partitioning (preserving relative order) of a range based on a predicate? A) std::partition B) std::stable_partition C) std::remove_if D) std::sort Answer: B Explanation: stable_partition keeps the original order of elements that satisfy the predicate and those that do not. Question 33. Which algorithm is most appropriate to eliminate consecutive duplicate elements from a sorted std::vector? A) std::unique B) std::remove C) std::erase D) std::unique_copy Answer: A Explanation: unique removes adjacent duplicates; when the range is sorted, all duplicates become adjacent. Question 34. What is the time complexity of std::stable_sort on a random-access range of size n? A) O(n log n) worst-case, O(n) best-case B) O(n²) worst-case C) O(n log² n) worst-case D) O(n) always Answer: A Explanation: stable_sort typically uses a merge-sort variant guaranteeing O(n log n) worst-case and linear time when the input is already sorted. Question 35. Which algorithm would you use to merge two already sorted vectors a and b into a third vector c without duplicates? A) std::merge followed by std::unique B) std::set_union C) std::inplace_merge D) std::copy Answer: B Explanation: set_union merges two sorted ranges and discards duplicate values.
Question 36. What does std::make_heap(v.begin(), v.end()); do? A) Sorts the vector in ascending order. B) Rearranges the elements to satisfy the heap property (max-heap by default). C) Converts the vector into a std::priority_queue. D) Removes the largest element from the vector. Answer: B Explanation: make_heap transforms the range into a heap representation suitable for subsequent push_heap/pop_heap. Question 37. After calling std::push_heap(v.begin(), v.end());, what must be true about the range [v.begin(), v.end())? A) It is a valid max-heap including the newly added element at v.back(). B) The vector is sorted. C) The smallest element is at v.front(). D) The heap property is violated for the first element. Answer: A Explanation: push_heap assumes the range [first, last-1) is already a heap and inserts the element at last-1 into the heap. Question 38. Which algorithm returns an iterator to the smallest element in a range? A) std::min_element B) std::max_element C) std::find_min D) std::lower_bound Answer: A Explanation: min_element scans the range and returns the iterator to the minimal value. Question 39. In the functional library, what does std::plus()(a, b) compute?
Question 43. Which manipulator forces floating-point output to always show the decimal point, even for whole numbers? A) std::fixed B) std::showpoint C) std::noshowpoint D) std::setprecision(0) Answer: B Explanation: showpoint ensures the decimal point and trailing zeros are displayed. Question 44. How would you set the output stream to display exactly three digits after the decimal point? A) std::cout << std::fixed << std::setprecision(3); B) std::cout << std::setprecision(3); C) std::cout << std::showpoint << std::setprecision(3); D) std::cout << std::noshowpoint << std::setprecision(3); Answer: A Explanation: fixed forces fixed-point notation; setprecision(3) then specifies three digits after the decimal. Question 45. Which stream flag controls whether bool values are printed as true/false instead of 1/0? A) std::boolalpha B) std::noboolalpha C) std::showbase D) std::uppercase Answer: A Explanation: boolalpha toggles textual representation of boolean values. Question 46. Which of the following correctly opens a file for both reading and writing in binary mode? A) std::fstream file("data.bin", std::ios::in | std::ios::out | std::ios::binary); B) std::ifstream file("data.bin", std::ios::binary); C) std::ofstream file("data.bin", std::ios::binary); D) std::fstream file("data.bin", std::ios::app | std::ios::binary); Answer: A
Explanation: Combining in and out with binary creates a read/write binary stream. Question 47. What does std::stringstream ss("123 45"); int a,b; ss >> a >> b; set a and b to? A) a = 123, b = 45 B) a = 45, b = 123 C) a = 0, b = 0 D) Compilation error Answer: A Explanation: Extraction operators read whitespace-separated tokens sequentially. Question 48. Which smart pointer exclusively owns a dynamically allocated object and cannot be copied? A) std::shared_ptr B) std::weak_ptr C) std::unique_ptr D) std::auto_ptr Answer: C Explanation: unique_ptr enforces sole ownership; copy operations are deleted. Question 49. How can you create a std::shared_ptr that shares ownership with an existing std::shared_ptr p? A) std::shared_ptr q = p; B) std::shared_ptr q(p.get()); C) std::shared_ptr q = std::make_shared(*p); D) std::shared_ptr q = std::move(p); Answer: A Explanation: Copy-constructing a shared_ptr increments the reference count. Question 50. Which declaration uses auto to deduce the type of a lambda that captures x by value? A) auto f = [x]() { return x; }; B) auto f = [&x]() { return x; }; C) auto f = []() { return x; }; D) auto f = [=]() -> int { return x; }; Answer: A Explanation: [x] captures by value; auto deduces the lambda’s closure type.
C) Creates a bound function object without invoking it. D) Causes a compilation error because invoke expects a callable object, not a pointer. Answer: A Explanation: std::invoke correctly handles member function pointers, calling them with the supplied object and arguments. Question 55. Which of the following statements about std::move is correct? A) It copies the object to a new location. B) It casts its argument to an rvalue reference, enabling move semantics. C) It permanently destroys the original object. D) It is only usable with built-in types. Answer: B Explanation: std::move performs a static cast to an rvalue reference, signalling that the object may be moved from. Question 56. Which overload of std::swap will be selected for a user-defined type MyType that provides a member swap(MyType&)? A) std::swap(MyType&, MyType&) (the generic template) B) ADL-found swap(MyType&, MyType&) in the same namespace as MyType C) The member function MyType::swap is never considered. D) Compilation error due to ambiguity. Answer: B Explanation: Argument-dependent lookup (ADL) finds a non-member swap in the namespace of MyType; the generic std::swap will forward to that. Question 57. Which of the following correctly creates a std::unique_ptr to an array of 10 ints? A) std::unique_ptr p(new int[10]); B) std::unique_ptr p(new int[10]); C) std::unique_ptr p; D) std::make_unique(10);
Answer: A Explanation: For dynamic arrays, the deleter must be delete[], which unique_ptr provides. Question 58. What is the result of std::distance(v.begin(), v.end()) for a std::vector of size 5? A) 5 B) 4 C) Undefined D) Depends on iterator category Answer: A Explanation: distance computes the number of increments needed, which equals the container’s size for random-access iterators. Question 59. Which iterator category is required for the algorithm std::rotate? A) Input iterator B) Forward iterator C) Bidirectional iterator D) Random-access iterator Answer: B Explanation: rotate only needs forward iterators; it moves elements by splicing sub-ranges. Question 60. In a std::map, what does the expression m["key"] do if "key" is not present? A) Inserts a new element with default-constructed value and returns a reference to it. B) Throws std::out_of_range. C) Returns a reference to a static dummy value. D) Causes undefined behavior. Answer: A
A) insert B) push_back C) emplace_front D) splice Answer: A Explanation: list::insert inserts before the iterator; to insert after, you pass std::next(it). The operation is still O(1). Question 65. In the context of templates, what does the term “SFINAE” stand for? A) Substitution Failure Is Not An Error B) Simple Function Interface Not Allowed Externally C) Standard Function Inlining Not Applicable D) None of the above Answer: A Explanation: SFINAE allows overload resolution to discard templates that fail substitution without causing a hard error. Question 66. Which of the following is a valid use of std::enable_if to restrict a function template to integral types? A) template , int> = 0> void foo(T); B) template std::enable_if::value> foo(T); C) template void foo(T) requires std::is_integral_v; D) All of the above (C requires C++20) Answer: D Explanation: All three forms constrain the template to integral types; (C) uses concepts introduced in C++20. Question 67. Which overload of std::find_if can be used with a std::forward_list? A) std::find_if(std::forward_list::iterator, std::forward_list::iterator, Pred) B) std::find_if(std::forward_list::const_iterator, std::forward_list::const_iterator, Pred) C) Both A and B D) Neither; find_if requires random-access iterators.
Answer: C Explanation: find_if works with any input iterator, and forward_list provides both mutable and const iterators. Question 68. Which algorithm returns the number of elements satisfying a predicate in a range? A) std::count_if B) std::accumulate C) std::transform_reduce D) std::partial_sum Answer: A Explanation: count_if iterates and increments a counter for each element where the predicate returns true. Question 69. When using std::generate_n(it, n, gen), how many times is the generator gen invoked? A) Exactly n times. B) n-1 times. C) Until gen returns false. D) Undefined. Answer: A Explanation: generate_n calls gen for each of the n positions, assigning the result. Question 70. Which of the following statements about std::array is correct? A) Its size is fixed at compile time and it cannot be resized. B) It supports dynamic allocation via new. C) It provides push_back. D) It is a synonym for std::vector. Answer: A Explanation: std::array is a thin wrapper around a C-style array with fixed size N. Question 71. Which iterator type does std::istream_iterator model?