Reputation: 11
I'm trying to find string tp inside an unordered_map but it's giving me problems.
unordered_map < string, int > pastPoints;
int t = 0;
void doStuff(int x, int y) {
pair < int, int > tp_ = {x, y};
string tp = int_string(tp_);
if (find(pastPoints.begin(), pastPoints.end(), tp) != pastPoints.end()) {
ans = max(ans, t - pastPoints[tp]);
}
pastPoints[tp] = t;
}
It's giving me this error:
error: no match for ‘operator==’ (operand types are ‘std::pair<conststd::basic_string<char>, int>’ and ‘const std::basic_string<char>’)
{ return *__it == _M_value; }
Am I using unordered_map::find wrong? I'm finding the key which is a string.
Upvotes: 1
Views: 65
Reputation: 96941
Yes, you're using it wrong.
Don't use std::find
with maps and sets. It will check the elements one by one, while maps/sets have a faster way to search for elements.
Do this: pastPoints.find(tp)
.
Also using pastPoints[tp]
after a successful find
is wasteful, since it searches the map again. Instead, dereference the iterator returned by find
.
Example:
if (auto it = pastPoints.find(tp); it != pastPoints.end())
ans = max(ans, t - *it);
Upvotes: 1