Move last element of vector<vector<int>> to beginning

I need to move last element of vector<vector<int>> to beginning. I tried std::rotate , but it works only on integers. Also i tried std::move but I failed. How I can do this? Thank you in advance.

1 answer

  • answered 2018-01-13 20:39 Ron

    To place the last element at the beginning you can utilize the std::rotate function with reverse iterators. This performs a right rotation:

    #include <iostream>
    #include <vector>
    #include <algorithm>
    int main() {
        std::vector<int> v{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };
        std::rotate(v.rbegin(), v.rbegin() + 1, v.rend());
        for (auto el : v) {
            std::cout << el << ' ';

    To swap the first and last element utilize the std::swap function with vector's front() and back() references:

    std::swap(v.front(), v.back());

    The std::rotate function is not dependent on the type.