Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find index of element in vector of pairs

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!

like image 385
MM1 Avatar asked Jun 28 '20 19:06

MM1


People also ask

How do you find the index element of a vector?

Access an element in vector using vector::at() reference at(size_type n); reference at(size_type n); reference at(size_type n); It returns the reference of element at index n in vector.

How do you find the element of a vector in pairs?

We can search a pair in a sorted vector of pairs by using the built-in function “binary_search()”of STL library. We can search a first element of a pair in a sorted vector of pairs by using the built-in function “binary_search()”of the STL library.

What is the index of a vector?

Index vectors, or IV, represent the widest, weak-strong range of pointing. In that, they are represented by an actual arrow that points in the direction that the individuals being filmed in a shot are actually looking.


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; }));
like image 56
kesarling He-Him Avatar answered Oct 25 '22 10:10

kesarling He-Him


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.

like image 44
Tony Delroy Avatar answered Oct 25 '22 11:10

Tony Delroy