I have a function that takes a std::vector of doubles, and copies them to another vector, but at a particular offset (assume there is sufficient space):
void copy_stuff(const std::vector<double> & data,
std::vector<double> & dest,
size_t dest_offset) {
std::copy(data.begin(), data.end(), dest.begin() + dest_offset);
}
This results in a C++11 clang compiler -Weverything warning centered on the + dest_offset part:
Implicit conversion changes signedness: 'size_t' (aka 'unsigned long') to 'difference_type' (aka 'long').
I'm not sure how I should cast the expression dest.begin() + dest_offset in order to eliminate this warning. Casting the result to a double * does not compile:
std::copy(data, data + data_size, static_cast<double *>(dest.begin() + dest_offset));
Cannot cast from type 'std::__1::__wrap_iter' to pointer type 'double *'.
I had considered using vector indexing and then taking the address:
std::copy(data, data + data_size, &dest[dest_offset]);
This seems to eliminate the warning in this case, but doesn't compile if I try to use the same pattern with the source vector, i.e. with an offset involved with the first or second parameter of std::copy. For example:
static void copy_stuff_differently(const std::vector<double> & data,
std::vector<double> & dest,
size_t offset) {
std::copy(data.begin() + offset, data.end(), dest.begin());
}
Gives the same original warning of implicit conversion on the + offset. Attempting to use the address-of-index might suggest:
std::copy(&data[offset], data.end(), dest.begin());
Or a different but similar case:
std::copy(data.begin(), &data[offset], dest.begin());
However both cause a similar error:
test.cpp:8:3: error: no matching function for call to 'copy'
std::copy(&data[offset], data.end(), dest.begin());
^~~~~~~~~
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/iterator:1286:48: note:
candidate template ignored: deduced conflicting types for parameter '_Ip' ('const double *' vs.
'std::__1::__wrap_iter<const double *>')
template <class _Ip, class _Op> friend _Op copy(_Ip, _Ip, _Op);
^
I'm looking for a consistent and warning-free way to handle such offsets. What is the right way to handle offsets into a vector and avoid such errors and warnings?
std::next(std::begin(), dest_offset)change anything? - M.M