For a coding test, I have the following function:
static bool exists (int ints[], int size, int k)
The goal is to return true if k is in ints else return false.
Using the std library, one could do this:
static bool exists (int ints[], int size, int k) {
return std::binary_search(std::begin(ints), std::end(ints), k);
}
However, std::begin() only works with C-style arrays if the size is known to the compiler, from what I've been able to gather. I'm not sure why that is the case though.
Is there a way to achieve what I want without writing a custom iterator to handle it? Is it even possible to write such an iterator?
Using std::vector instead is not an option, since I can't change the function definition. Copying the array to a std::vector before calling std::binary_search() also seems like a waste of CPU time.
std::beginandstd::end? You can have this effect withstd::binary_search(ints, ints + size, k);. Or withstd::array/std::vector.std::beginandstd::endexisted.std::beginandstd::enddon't work with pointers. But a pointer is a valid kind of iterator, so you can use pointers instead ofstd::beginandstd::endas long as those pointers refer to a contiguous range of elements. So you can useintsas thebeginiterator andints + sizeas theenditerator.std::binary_searchis only valid ifints[]is sorted, which you did not mention in the question.