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"but it works only on integers" Why do you say that?David G– David G2018-01-13 20:42:23 +00:00Commented Jan 13, 2018 at 20:42
-
1How about std::swap?user2100815– user21008152018-01-13 20:42:28 +00:00Commented 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.Pawel J– Pawel J2018-01-13 20:50:41 +00:00Commented 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.Pawel J– Pawel J2018-01-13 20:50:45 +00:00Commented Jan 13, 2018 at 20:50
Add a comment
|
1 Answer
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.