Find index of element in vector of pairs

Viewed 2698

As stated in the title, I'm trying to find the index of an element in a vector of pairs. I have the following vector: std::vector<std::pair<std::string, double>> dict. The content of my dict is:

Name1 11
Name2 9
Name3 10
Name4 12
Name5 13

All I have in order to find the index is the first attribute of the pair. For example I have Name5 and I would like to find 4. (Since Name5 is the fifth element). Does anyone have an idea how to do it ? I tried something but it doesn't seem to work:

auto it = std::find(dict.begin(), dict.end(), movieName);

where movieName is an std::string with "Name5" inside. Thank you!

2 Answers

I would simply go with a normal for_each loop.

So:

int index = 0;
for(const auto& pair : dict) {
    if(pair.first == <whatever>) {
        break;
    }
    index++;
}

//if index == dict.size() then print element not found 

Other way would be using std::find_if() ( Thanks @Tony Delroy :) )

auto index = std::distance(dict.begin(), std::find_if(dict.begin(), dict.end(), [&](const auto& pair) { return pair.first == movieName; }));

You can use a predicate to decide which entries in the vector should match. It's easiest to do that with a lambda:

auto it = std::find_if(dict.begin(), dict.end(),
              [&](const auto& pair) { return pair.first == movieName; });

After you have the iterator, compare it to dict.end() to see if there was any match, and if there's a match you can convert it to an index into the vector using std::distance(), as d4rk4ng31 commented under the question.

Related