2

Found this code while doing code review:

std::array<uint, 10> expArray2 = {92,130,169,951,634,187,377,233,865,944};
copy(&expArray2[0], &expArray2[10], back_inserter(expected));
                        ^~~~Is this Undefined behavior as ArrayIndexOutOfBoundAccess?

Is it same as (what I propose) :

std::copy ( expArray2, expArray2+10, expected.begin() ); 

My colleague says 1.) both are same 2.) there is no undefined behavior?

I explained to him that pointers and iterator are two different things, along with std::copy signature:

template <class InputIterator, class OutputIterator>
  OutputIterator copy (InputIterator first, InputIterator last, OutputIterator result); 

Could someone please confirm/explain this to me if I am wrong anywhere?

Community
  • 1
  • 1
Saurav Sahu
  • 13,038
  • 6
  • 64
  • 79

2 Answers2

3

This std::copy usage with std::array is perfectly valid. Basically std::copy works with pointers denoting the input range because pointers satisfy all the requirements of the input iterators.

As for taking begin end end of the input range as &expArray2[0] and &expArray2[10] it is also fine because std::array is guaranteed to manage a continuous underlying array so you can deal with this array as with any usual C-style array.

As for me, I would prefer to use std::begin and std::end inside std::copy:

std::copy(std::cbegin(expArray2), std::cend(expArray2),
    std::back_inserter(expected));
Edgar Rokjān
  • 17,245
  • 4
  • 40
  • 67
1

Your colleague is right.

Iterator is a concept with requirements (that they can be dereferenced and incremented is a minimum) that pointers fullfil.

Also, ranges in C++ are half open, which means that the second (last) iterator passed to algorithms needs to be one past the elements you want included in the range. It's never dereferenced (that's guaranteed by C++ standard), so there's no UB the code you posted.

NOTE: expected.begin() is not the same as back_inserter(expected). With the former you need a container big enough to hold the resulting range, while the latter automaticaly expands it.

jrok
  • 54,456
  • 9
  • 109
  • 141