C++11 Best way of changing order of arbitrary elements in a vector into arbitrary positions?

What would be the best way to do the following?

I would like to reverse a smaller range in a vector and haven't found any better solution than this: I extract the smaller range to a newly created vector, reverse it and then add the newly created vector at the former position in the original vector.

Another way to explain what I want to do is something like this:

Original vector: 1 2 3 4 5 6 7 8 9 10 11.

Wanted result:   1 2 3 4 5 6 7 10 9 8 11.

1. Copy 10, 9, 8 in that order into a new vector with three element or copy element 8, 9, 10 into a new vector an reverse it. The original vector consists now of nine elements because the elements 8, 9, 10 were erased in the procedure.

2.The new vector with the 3 elements 10, 9, 8 is then copied/appended into the original vector at position 8 as a vector or element by element at position 8, 9, 10 respectively.

I am sure there are better solutions then the method mentioned above.

Bo  Nystedt
That's a little bit crazy.
https://joycemoreno.bandcamp.com/album/just-a-little-bit-crazy

All STL algorithms work on a range. Typically, begin/end are passed to process the whole container, but you don't have to pass the whole range all the the time irrespective of your needs.

Just reverse the part you're interested in.
http://en.cppreference.com/w/cpp/algorithm/reverse
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <vector>
#include <algorithm>
#include <iterator>
#include <iostream>

int main()
{
        std::vector<int> v{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

        auto begin = v.begin();
        auto end = v.begin();
        std::advance(begin, 2);
        std::advance(end, 5);
        std::reverse(begin, end);

        for (int i : v)
                std::cout << i << ", ";
        std::cout << "\n";
}
Last edited on
Topic archived. No new replies allowed.