c++ find in pair

To find an element in a pair in C++, you can use the find function from the <algorithm> library. Here are the steps to use it:

  1. Include the necessary libraries:
#include <algorithm>
#include <iostream>
#include <vector>
  1. Create a vector of pairs:
std::vector<std::pair<int, std::string>> myPairs;
  1. Populate the vector with pairs:
myPairs.push_back(std::make_pair(1, "Apple"));
myPairs.push_back(std::make_pair(2, "Banana"));
myPairs.push_back(std::make_pair(3, "Orange"));
  1. Use the find function to search for a specific element in the vector of pairs:
int searchKey = 2;
auto it = std::find_if(myPairs.begin(), myPairs.end(), [searchKey](const std::pair<int, std::string>& element) {
    return element.first == searchKey;
});
  1. Check if the element was found:
if (it != myPairs.end()) {
    std::cout << "Element found: " << it->first << ", " << it->second << std::endl;
} else {
    std::cout << "Element not found." << std::endl;
}

In the above code, we use the find_if function with a lambda expression as the predicate. The lambda expression checks if the first member of each pair is equal to the searchKey. If a match is found, the iterator it will point to the pair in the vector.

Finally, we check if the iterator it is equal to myPairs.end(), which indicates that the element was not found. If the element is found, we can access its values using the first and second members of the pair.