Search code examples
c++c++11copystdvectorstl-algorithm

std::copy_n doesn't change destination vector size


If I reserve some space for a vector, and then I copy some values in it with std::copy_n(), I get the values copied correctly and accessible, but the size of the vector is still zero. Is this the expected behaviour? Should I resize the vector instead, even if it is not as efficient?

#include <algorithm>
#include <iostream>
#include <vector>

int main()
{
    std::vector<double> src, dest;

    for(double x = 0.0; x < 100.0; ++x)
        src.push_back(x);

    dest.reserve(src.size());

    std::copy_n(src.cbegin(), src.size(), dest.begin());

    std::cout << "src.size() = " << src.size() << std::endl;
    std::cout << "dest.size() = " << dest.size() << std::endl;

    for(size_t i = 0; i < src.size(); ++i)
        std::cout << dest[i] << "  ";

}

Compilers tested: clang, gcc, Visual C++


Solution

  • but the size of the vector is still zero

    std::copy_n won't change the size of the container, just copy the value and step the iterators; it even doesn't have any information about the container. So the code has undefined behavior, even it seems to work fine.

    Should I resize the vector instead, even if it is not as efficient?

    Yes you could use std::vector::resize instead of std::vector::reserve to solve the issue. As you might have thought, it means all the elements will be constructed by resize firstly, then assigned by copy_n.

    You could use std::back_inserter, which will append elements at the end of the container by invoking the container's push_back() member function (i.e. construct elements directly), thus increase the container's size. e.g.

    dest.reserve(src.size());
    std::copy_n(src.cbegin(), src.size(), std::back_inserter(dest));