![]() |
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"} Find a Pair by Key in a Vector of Pairs in C++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. C++ Program to Find Pair by Key in Vector of PairsC++
Output
Pair found with first element: 2 and second element: Two Time Complexity: O(N) where N is the number of elements in vector. We can prefer std::map or std::unordered_map containers instead of vector of pairs for better efficiency. |
Reffered: https://www.geeksforgeeks.org
C++ |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 14 |