Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find a value in a sorted C++ vector in the most efficient way?

I have looked at find and binary_search, but find doesn't take advantage of the fact that the vector is sorted, and binary_search only returns a true or false, not where it found the value. Is there any function that can give me the best of both worlds?

like image 490
user2813274 Avatar asked Sep 25 '13 01:09

user2813274


People also ask

How do you find the elements in a sorted vector?

You can use find to locate a particular element in any container in time O(N). With vector you can do random access and take advantage of the lower_bound (log2(N)), upper_bound, or equal_range class of std algorithms. std::lower_bound will do that for you.

Can we sort vector using sort function?

Sorting a Vector in C++ in Ascending orderA vector in C++ can be easily sorted in ascending order using the sort() function defined in the algorithm header file. The sort() function sorts a given data structure and does not return anything. The sorting takes place between the two passed iterators or positions.

Is vector sorted C++?

Vector elements are not sorted in ascending order. Vector elements are sorted in ascending order.

How do you create a sorted vector?

An unsorted vector can be sorted by using the function std::sort() : std::vector<int> v; // add some code here to fill v with some elements std::sort(v. begin(), v.


1 Answers

You can use find to locate a particular element in any container in time O(N). With vector you can do random access and take advantage of the lower_bound (log2(N)), upper_bound, or equal_range class of std algorithms. std::lower_bound will do that for you. It's in the equivalent-behavior section at the top for binary_search. However, the utility of binary_search is limited to yes and no answers (maybe the naming needs to be improved in the future version of C++; binary_in()).

like image 193
Steve Howard Avatar answered Sep 20 '22 07:09

Steve Howard