0

how can i get the second element of a vector pair from specific first element?

I have codes below:

vector< pair <string, string> > vect;
vect.push_back(make_pair("hello","s:hihi"));
vect.push_back(make_pair("hi","s:hello"));
string check;
string first;
string last;
while(true)
{
    cout << "Create new pair.\nFirst element: ";
    //Part1
    getline(cin, first);
    cout << "Second element: ";
    //Part2
    getline(cin, last);
    if(first == "get" && last == "get") break;
    else vect.push_back(make_pair(first, last));
}
cout << "What first element to search: ";
//Part3
getline(cin, check);

I want to check if user entered hello at part3, it will cout s:hihi. By this way if user entered hi at part3, it will cout s:hello. If user entered "bye" at part 1 and entered "hey" at part 2. Then when user enter "bye" at part 3 it will print out "hey"

How can I do this?

Atomic
  • 3
  • 3

1 Answers1

1

If you insist on using a std::vector<std::pair<std::string, std::string>> instead of std::map or std::unordered_map then I would suggest something like this:

auto it = std::find_if(std::begin(vect), std::end(vect), [&check](const auto & pair){
        return pair.first.compare(check) == 0;}); // this returns the iterator to the pair
(*it).second // << access to the second string 

This uses std::find_if which takes a lambda.

But like the comments have already stated, this is the perfect scenario for maps.

V41U
  • 156
  • 2
  • 10