Search code examples
c++vectormultidimensional-arraymovestdvector

In c++ how to move range elements for a vector of vectors


Say I have a:

std::vector<std::vector<int> > indices;

I fill these up, where each index of both outer and inner vectors have 3 entries. Now I want to do something similar to applying std:move_backward() on single vector-containers.

Let me give an example. Here is my initial container filled at the following indices:

[0][0][0][1][0][2] , [1][0][1][1][1][2] , [2][0][2][1][2][2] , [3][0][3][0][3][0]

After moving from an i-th element backwards, in this example: the outer-index [1], I would get:

[0][0][0][1][0][2] , [1][0][1][1][1][2] , [1][0][1][1][1][2] , [2][0][2][1][2][2]

Basically, the outer-index [1] is placed in [2], and [3] is replaced by the original [2], moving the inner-vectors along with it.

Any ideas on how this can be done? Perhaps with a function template?


Solution

  • This should do what you describe:

    std::copy_backward(indices.begin()+1, indices.begin()+3, indices.end());
    

    No special manipulation of the inner vector is necessary.