I got a compiling error when using std::copy to convert a 1D vector to a 2D vector.
int main()
{
std::vector< std::vector<float> > v2D(10, std::vector<float>(10, 0.0));
std::vector<float> v1D(100, 0.0);
for (int i = 0; i < 100; ++i)
v1D.push_back(i);
for (unsigned int j = 0; j < 10; j++)
{
std::copy(v1D.begin() + j * 10, v1D.begin() + (j + 1) * 10, std::back_inserter(v2D[j].begin()));
}
}
Would you please help solve this proplem? Thank you.
std::back_insertertakes a container, not an iterator. Changestd::back_inserter(v2D[j].begin())tostd::back_inserter(v2D[j]). Note that this will be calling.push_back()on thestd::vector<float>atv2D[j], so you probably also want to changestd::vector< std::vector<float> > v2D(10, std::vector<float>(10, 0.0));tostd::vector< std::vector<float> > v2D(10);.Alternatively, you can change
std::back_inserter(v2D[j].begin())tov2D[j].begin(). This works becausestd::copywants an output iterator, andstd::vector<>::iteratorbehaves as one when there are a sufficient number of elements in thevector<>to overwrite. And this way, your current initialization ofv2Dis already ideal.EDIT: Someone else said this in a separate answer then deleted it, so I’ll say it on their behalf because it’s definitely noteworthy: because you initialize
v1Dwith 100 elements, the [1..100] digits you thenpush_backare appended to the initial 100 elements (which all have your specified value of 0) rather than overwriting them. You should changestd::vector<float> v1D(100, 0.0);tostd::vector<float> v1D;to get the behavior you apparently want (orstd::vector<float> v1D; v1D.reserve(100);if you’re really being pedantic about efficiency).