0

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.

4
  • 1
    "but it works only on integers" Why do you say that? Commented Jan 13, 2018 at 20:42
  • 1
    How about std::swap? Commented Jan 13, 2018 at 20:42
  • @0x499602D2 I read that on reddit, but now I can see it's not true. I'm trying to use it right now. Commented Jan 13, 2018 at 20:50
  • @NeilButterworth I must take the last element and put it to the beginning. I can't swap them because I can't mess up the order. Commented Jan 13, 2018 at 20:50

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.