Advantages of std :: find

Is there any advantage to using C ++ 11 std::find over find container?

  • In the case of std::vector (which does not have a find method) does std::find some smart algorithm or a naive way to simply iterate over each element?

  • In the case of std::map it seems you need to go along std::pair , which is the value_type for std::map . This does not seem very useful, as usual you want to find for either the key or the displayed item.

  • What about other containers like std::list or std::set or std::unordered_set ?

+3
c ++ find c ++ 11 stl containers
Jun 22 '13 at 22:40
source share
1 answer

In the case of std :: vector (which doesn't have a search method) does std :: find use some kind of smart algorithm or a naive way to simply iterate over each element?

It cannot, because the vectors are not sorted. There is no other way to find an element in an unsorted vector, except for a linear search with complexity O (n).

On the other hand, sequence containers do not offer find() member functions, so you cannot use this.

In the case of std :: map, it seems that you need to go through std :: pair, which is the value_type for std :: map. This does not seem very useful, as you usually need to find for either the key or the displayed item.

In fact, here you should use the find() member function, which guarantees better complexity (O (log N)).

In the general case, when a container provides a member function with the same name as the general algorithm, this is because the member function does the same, but offers the best guarantee of complexity.

What about other containers like std :: list or std :: set or std :: unordered_set?

Just like std::vector , std::list not a sorted container - therefore the same output applies.

For std::set and std::unordered_set , you should use the find() member function instead, which guarantees better complexity (O (log n) and average O (1), respectively).

+9
Jun 22 '13 at 22:45
source share



All Articles