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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.