简体   繁体   中英

Using std::begin and std::end with array with run-time size

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.

You cannot use std::begin() or std::end() as you want to because, as Andrieux pointed out in a comment, what appears to be an array-type in the function's argument-list is just a pointer. This is confirmed by the fact that the second argument to the function is the number of elements. Such an argument would not be necessary if the information needed by std::end() were present in ints[] .

As each of the first four comments that I saw at the time of this writing indicated, however, the pointer that is passed in is an iterator. In fact, an ordinary pointer has all of the properties of a random-access iterator.

So, yes, you don't need to come up with your own kind of iterator. Just use the passed-in pointer as the commenters indicated.

static bool exists (int ints[], int size, int k) {
  return std::binary_search(ints, ints + size, k);
}

However, calling std::binary_search() is the right thing to do only if the elements of ints[] be ordered so that std::binary_search() will work. You did not state that in your post.

As to whether it be possible to write an iterator like what you might want, the answer is "yes," but it is unnecessary because a pointer is already the right kind of iterator to input to std::binary_search() .

You are right that using std::vector in the body would be a waste of time.

You could have done exactly as you originally wanted if both the input-array were ordered, and the signature of the function had instead been

template<int size> bool exists (int (&ints)[size], int k);

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