Reputation: 13
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.
Upvotes: 0
Views: 2651
Reputation: 15511
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.
Upvotes: 2