10 C++ STL Interview Questions and Answers
Prepare for your C++ interview with this guide on mastering the Standard Template Library (STL) through common and advanced questions.
Prepare for your C++ interview with this guide on mastering the Standard Template Library (STL) through common and advanced questions.
The C++ Standard Template Library (STL) is a powerful set of C++ template classes to provide general-purpose classes and functions with templates that implement many popular and commonly used algorithms and data structures like vectors, lists, queues, and stacks. Mastery of the STL is crucial for writing efficient and maintainable C++ code, making it a key area of focus for anyone looking to excel in C++ programming.
This article offers a curated selection of interview questions specifically focused on the C++ STL. By working through these questions and understanding the underlying concepts, you will be better prepared to demonstrate your proficiency in C++ and the STL during technical interviews.
To solve this problem, we can use the std::vector
container to store integers and calculate their sum. Here’s a simple implementation:
#include <iostream> #include <vector> int sumOfElements(const std::vector<int>& vec) { int sum = 0; for (int num : vec) { sum += num; } return sum; } int main() { std::vector<int> numbers = {1, 2, 3, 4, 5}; std::cout << "Sum of elements: " << sumOfElements(numbers) << std::endl; return 0; }
To find the first element in a vector greater than a given value, use the find_if
algorithm with a predicate:
#include <iostream> #include <vector> #include <algorithm> int findFirstGreaterThan(const std::vector<int>& vec, int value) { auto it = std::find_if(vec.begin(), vec.end(), [value](int i) { return i > value; }); if (it != vec.end()) { return *it; } else { throw std::runtime_error("No element greater than the given value found."); } } int main() { std::vector<int> vec = {1, 3, 5, 7, 9}; int value = 4; try { int result = findFirstGreaterThan(vec, value); std::cout << "First element greater than " << value << " is " << result << std::endl; } catch (const std::runtime_error& e) { std::cout << e.what() << std::endl; } return 0; }
To sort a vector of strings in descending order, use std::sort
with a custom comparator:
#include <iostream> #include <vector> #include <algorithm> int main() { std::vector<std::string> vec = {"apple", "orange", "banana", "grape"}; std::sort(vec.begin(), vec.end(), std::greater<std::string>()); for (const auto& str : vec) { std::cout << str << " "; } return 0; }
To insert key-value pairs into a map and retrieve a value, use std::map
:
#include <iostream> #include <map> #include <string> void insertAndRetrieve() { std::map<std::string, int> myMap; myMap["apple"] = 1; myMap["banana"] = 2; myMap["cherry"] = 3; std::string key = "banana"; if (myMap.find(key) != myMap.end()) { std::cout << "The value for key '" << key << "' is: " << myMap[key] << std::endl; } else { std::cout << "Key '" << key << "' not found in the map." << std::endl; } } int main() { insertAndRetrieve(); return 0; }
A custom comparator can define a specific sorting order for a set. Here, we sort strings by length:
#include <iostream> #include <set> #include <string> struct LengthComparator { bool operator()(const std::string& a, const std::string& b) const { return a.length() < b.length(); } }; int main() { std::set<std::string, LengthComparator> mySet = {"apple", "banana", "kiwi", "cherry"}; for (const auto& str : mySet) { std::cout << str << std::endl; } return 0; }
std::transform
to convert a vector of integers to their squares.Use std::transform
to convert a vector of integers to their squares:
#include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> vec = {1, 2, 3, 4, 5}; std::vector<int> result(vec.size()); std::transform(vec.begin(), vec.end(), result.begin(), [](int x) { return x * x; }); for (int n : result) { std::cout << n << " "; } return 0; }
Handle exceptions when accessing elements out of bounds in a vector:
#include <iostream> #include <vector> #include <stdexcept> void accessElement(const std::vector<int>& vec, size_t index) { try { int value = vec.at(index); std::cout << "Element at index " << index << " is " << value << std::endl; } catch (const std::out_of_range& e) { std::cerr << "Error: " << e.what() << std::endl; } } int main() { std::vector<int> myVector = {1, 2, 3, 4, 5}; accessElement(myVector, 2); accessElement(myVector, 10); return 0; }
Implement a custom hash function for an unordered_map storing pairs of integers:
#include <iostream> #include <unordered_map> #include <utility> struct pair_hash { template <class T1, class T2> std::size_t operator() (const std::pair<T1, T2>& p) const { auto hash1 = std::hash<T1>{}(p.first); auto hash2 = std::hash<T2>{}(p.second); return hash1 ^ hash2; } }; int main() { std::unordered_map<std::pair<int, int>, std::string, pair_hash> umap; umap[std::make_pair(1, 2)] = "one-two"; umap[std::make_pair(3, 4)] = "three-four"; for (const auto& elem : umap) { std::cout << "(" << elem.first.first << ", " << elem.first.second << "): " << elem.second << std::endl; } return 0; }
Lambda expressions provide a way to create inline functions. Here’s an example with std::sort
:
#include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> numbers = {5, 2, 9, 1, 5, 6}; std::sort(numbers.begin(), numbers.end(), [](int a, int b) { return a < b; }); for (int n : numbers) { std::cout << n << " "; } return 0; }
Lambdas can also capture variables from their scope:
#include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> numbers = {1, 2, 3, 4, 5}; int factor = 2; std::for_each(numbers.begin(), numbers.end(), [factor](int &n) { n *= factor; }); for (int n : numbers) { std::cout << n << " "; } return 0; }
Range-based for loops offer benefits like improved readability and safety by reducing boilerplate code and minimizing errors:
#include <iostream> #include <vector> int main() { std::vector<int> numbers = {1, 2, 3, 4, 5}; // Traditional for loop for (std::vector<int>::iterator it = numbers.begin(); it != numbers.end(); ++it) { std::cout << *it << " "; } std::cout << std::endl; // Range-based for loop for (int num : numbers) { std::cout << num << " "; } std::cout << std::endl; return 0; }