简体   繁体   中英

How to sort an array of structs with std::binary_search or std::sort

I have a sorted array of structs. I want to use std::binary_search or std::find on it.

Everywhere I look, I find examples which show how to do it with a vector of structs. Never with an array of structs. I am not sure if I must use a predicate or overload the = operator or what.

What must be the third parameter to std::find if I am using the following call:

template< class InputIt, class T > InputIt find( InputIt first, InputIt last, const T& value );

Also, it says that the above calls will return an Iterator or return the last. How does this work with structs. Structs don't have iterators, do they ?

If you want to apply it to the (valid)array range [a, b) of an array arr , InputIt should be std::begin(arr) + a , and OutputIt should be std::begin(arr) + b . If b is equal to the number of elements in arr , then you can set OutputIt to std::end(arr) as well.

std::begin and std::end called on an array of type T return T*. Thus, you can always substitute T* for InputIt and OutputIt when thinking of these functions on arrays. std::find returns an InputIt. So, what you get is a pointer to the appropriate array element. If nothing was found, it returns last .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM