I have a list with all the elements as struct of form
typedef struct person_node{
string name;
string country;
}person;
std::list<person> list;
The list is already sorted on person name.
How do I use the inbuilt binary_search() function in this?
I already know how to use this binary_search() on a list with only numbers as data, but I wonder how can I use it for such a list.
I am using this binary function as:
binary_search (list.begin(), list.end(), value, compare_function);
Only thing I don’t know is, “What should I enter in place of value, if I need to look for a specific name in the list?”
Also I want an iterator to point to that node, if found.
You enter a
personcontaining thenameyou want to find.Also note that
binary_searchis only rarely useful (it only tells you whether the item is present, not where it is in the collection. It is doubly useless on astd::list, because it requires random-access iterators to work at all well (whichstd::listdoesn’t provide).So, what you probably want is an
std::vector<person>orstd::deque<person>, which you’ll probably want to search withstd::lower_boundorstd::upper_bound.std::lower_boundandstd::upper_boundwill each return an iterator to the item they found, giving you access to that object.