Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What function in the std library is there to binary search a vector and find an element?

I've got a node struct

struct Node{CString text, int id;};

in a sorted vector.

I'm wondering if there's a function in algorithm that will do a binary search of the vector and find an element.

like image 640
baash05 Avatar asked Dec 15 '08 18:12

baash05


People also ask

How do you find the element in STD vector?

You can use the find function, found in the std namespace, ie std::find . You pass the std::find function the begin and end iterator from the vector you want to search, along with the element you're looking for and compare the resulting iterator to the end of the vector to see if they match or not.

Can you do binary search on a vector?

To search a target element in a vector we will be using the binarySearch() method of the Collections class. Parameters: The List type object on which binary search is to be performed. The value of the target element.

What is the function of binary search?

Binary search is an efficient algorithm for finding an item from a sorted list of items. It works by repeatedly dividing in half the portion of the list that could contain the item, until you've narrowed down the possible locations to just one. We used binary search in the guessing game in the introductory tutorial.

Is std :: find binary search?

The simple answer is: std::find for unsorted data and std::binary_search for sorted data.


2 Answers

std::binary_search() will tell you if a value exists in the container.

std::lower_bound()/std::upper_bound() will return an iterator to the first/last occurrence of a value.

Your objects need to implement operator< for these algorithms to work.

like image 65
Ferruccio Avatar answered Oct 10 '22 00:10

Ferruccio


Yes, there's a function called "binary_search" std::binary_search

You give it first, last and a value or a predicate.

See here for a sample

Combine that with Martin York's operator== and you should be OK (alternatively you can write a predicate functor

like image 33
Binary Worrier Avatar answered Oct 10 '22 02:10

Binary Worrier