0

Hello im wondering if its possible to copy a section of an array whilst initializing a vector.

For example I have tried

UINT16 myarray[] = { 0,1,2,3,4,5,6, ..., n };
std::vector<UINT16> myvect(myarray[3], myarray[3] + 16);

This kind of works however I seem to get more data than i intended. Is this the correct usage?

Jarod42
  • 203,559
  • 14
  • 181
  • 302
Chris
  • 179
  • 12

3 Answers3

1

The way is to pass iterators, not values

std::vector<UINT16> myvect(myarray + 3, myarray + 3 + 16);
Jarod42
  • 203,559
  • 14
  • 181
  • 302
1
UINT16 myarray[] = { 0,1,2,3,4,5,6, ..., n };
std::vector<UINT16> myvect(myarray[3], myarray[3] + 16);

This uses myarray[3] which is 3 and myarray[3] + 16 which is 19 as arguments to the myvect constructor. Which in turn sets up myvect to contain 3 elements, all with the value 19.

If you want a copy of the 16 elements starting at index 3, you can do it like this:

std::vector<UINT16> myvect(&myarray[3], &myarray[3 + 16]);
Sid S
  • 6,037
  • 2
  • 18
  • 24
  • Assuming size is greater than 19, else you have UB. (Where it is clear that `UINT16 myarray[7]` would produce UB, it is also the case for `UINT16 myarray[19]`). – Jarod42 Jan 08 '19 at 20:52
  • @Jarod42, It will work if size is 19, too. Anyway, this possible UB was present in the question and it's not what the OP was asking about. – Sid S Jan 08 '19 at 21:44
  • Seems there is a debate if `&*pointer` is `pointer` or not (and so UB or not)... So I would avoid it. See [may-i-take-the-address-of-the-one-past-the-end-element-of-an-array](https://stackoverflow.com/questions/3144904/may-i-take-the-address-of-the-one-past-the-end-element-of-an-array). – Jarod42 Jan 08 '19 at 21:52
0

Here is a different (more verbose) way:

uint16_t       myarray[]  = { 0, 1, 2, 3, 4, 5, 6, ..., n };
constexpr auto arr_size   = sizeof(myarray) / sizeof(myarray[0]);
constexpr auto copy_start = std::min< size_t >(3, arr_size);
constexpr auto copy_count = 19;
constexpr auto copy_end   = std::min< size_t >(copy_start + copy_count, arr_size);

vector< uint16_t > myvect(std::next(myarray, copy_start), std::next(myarray, copy_end));

Instead of UINT16 you can use uint16_t type from C++11 onwards: Fixed width integers (if your compiler supports it)

If your values are available at compile time, then you can use compile time constants(constexpr) to calculate the helper variables. Otherwise const should be used.

Standard algorithms can be used also on arrays so providing an offset to std::next can be used to get the n-th element of an array.

Robert Andrzejuk
  • 5,076
  • 2
  • 22
  • 31