Open In App

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

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




// C++ program to find the pair using its key in vector of
// pairs
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
  
int main()
{
    // Initialize a vector of pairs
    vector<pair<int, string> > vec
        = { { 10, "One" },
            { 2, "Two" },
            { 3, "Three" },
            { 40, "Four" } };
  
    // Key to search for
    int key
        = 2;
  
    // Use std::find_if to find the pair with the given key
    // The lambda function checks if the first element of
    // the pair is equal to the key
    auto it = find_if(
        vec.begin(), vec.end(),
        [key](const auto& p) { return p.first == key; });
  
    // If the iterator is not equal to the end of the
    // vector, the pair was found
    if (it != vec.end()) {
        cout << "Pair found with first element: "
             << it->first
             << " and second element: " << it->second
             << endl;
    }
    else {
        // If the iterator is equal to the end of the
        // vector, the pair was not found
        cout << "Pair not found" << endl;
    }
  
    return 0;
}

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.


Article Tags :