![]() |
VOOZH | about |
In C++, vectors are dynamic arrays that can automatically resize themselves according to the number of elements while pair allows the users to store two heterogeneous objects as a single unit. In this article, we will learn how to find a pair by key within a vector of pairs in C++.
Example:
Input: myVector = {{10, "One"}, {2, "Two"}, {3, "Three"},{40,"Four"}} Output: Pair found: {2, "Two"}
We can use the C++ STL algorithm std::find_if() to find the pair with the given key in the vector of pairs. We need to provide it with the custom unary predicate function that will return a boolean value for the matching case. We can create a lambda function for this purpose.
Pair found with first element: 2 and second element: Two
Time Complexity: O(N) where N is the number of elements in vector.
Auxilary Space: O(1)
We can prefer std::map or std::unordered_map containers instead of vector of pairs for better efficiency.