3 ms·
The first snippet you wrote makes sense for string, but not for vector. For vector, you'd need to do: if (x_Vec.find(another_x) != x_Vec.end()) { //so
by int_19h 8y ago
The first snippet you wrote makes sense for string, but not for vector. For vector, you'd need to do:
if (x_Vec.find(another_x) != x_Vec.end()) {
//some code
}
The reason why vector doesn't have contains() is because it would be an O(N) operation for a vector. STL is generally designed in such a way that, when something needs to do an O(N) lookup, it has to deal with iterators, making the iteration happening in the background a bit more explicit.
But, for example, for std::set and map, you can just do:
if (a_set.count(x)) { ... }
It's not a good pattern for multiset and multimap, since it won't stop at the first occurrence. C++20 finally added contains() for that reason - but, again, only to associative containers.
- LgWoodenBadger 8y agobut isn't find() an O(n) operation already?
- int_19h 8y agoIndeed! Which is why find() is not a member function on vector (so my snippet above is wrong - I just missed that part). It's a global function, so you need to do: if (find(x, v.begin(), v.end()) != v.end()) ... For maps and sets, find is a member function though. Same principle - if it is implemented in some optimized way, the class provides it directly, but not otherwise.
- rwbt 8y agoYes, I'd need to check for end iterator in vector. But my point still stands - C++ does have some weird ergonomics.