Olivier Grech Olivier Grech - 2 months ago 6
C++ Question

How to handle the case where the element copied by std::copy might be outside of the vector

I have a vector of undetermined length,

vSignal
.

I need to copy a part of
vSignal
into my dictionnary vector:

std::copy(vSignalIt1-n1, vSignalIt1, vDictionnary.begin());


vSignalIt1
is one of
vSignal
iterator.
My isssue is that, when I call the
copy()
function, I'm not sure if
vSignalIt1-n1
is pointing a value inside my vector.

I thought about doing a loop with a reverse iterator which would copy the value one by one until I reach the
rend()
of
vSignal
(in fact I did it and it worked).

But is there an alternative solution using the
copy()
function ?

EDIT:

A little precision: vDictionnary as a fixed size (n1) and in the case where I can't copy enough value from vSignal to fill it entirely, I complete it with 0.

Answer

You can use

const auto n2 = std::min(n1, std::distance(vSignal.begin(), vSignalIt1));

std::copy(vSignalIt1 - n2, vSignalIt1, vDictionnary.begin());
std::fill(vDictionnary.begin() + n2, vDictionnary.end(), 0);
Comments