GoldenLee
GoldenLee

Reputation: 747

Convert 1D vector to 2D vector

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.

Upvotes: 0

Views: 1274

Answers (1)

ildjarn
ildjarn

Reputation: 62975

std::back_inserter takes a container, not an iterator. Change std::back_inserter(v2D[j].begin()) to std::back_inserter(v2D[j]). Note that this will be calling .push_back() on the std::vector<float> at v2D[j], so you probably also want to change std::vector< std::vector<float> > v2D(10, std::vector<float>(10, 0.0)); to std::vector< std::vector<float> > v2D(10);.

Alternatively, you can change std::back_inserter(v2D[j].begin()) to v2D[j].begin(). This works because std::copy wants an output iterator, and std::vector<>::iterator behaves as one when there are a sufficient number of elements in the vector<> to overwrite. And this way, your current initialization of v2D is 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 v1D with 100 elements, the [1..100] digits you then push_back are appended to the initial 100 elements (which all have your specified value of 0) rather than overwriting them. You should change std::vector<float> v1D(100, 0.0); to std::vector<float> v1D; to get the behavior you apparently want (or std::vector<float> v1D; v1D.reserve(100); if you're really being pedantic about efficiency).

Upvotes: 4

Related Questions