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!
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With