VOOZH about

URL: https://www.geeksforgeeks.org/cpp/find-pair-by-key-in-vector-of-pairs-in-cpp/

⇱ How to Find a Pair by Key in a Vector of Pairs in C++? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Find a Pair by Key in a Vector of Pairs in C++?

Last Updated : 23 Jul, 2025

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 Pairs


Output
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.


Comment