To rotate items in a vector in C++, you can use the `std::rotate` algorithm provided by the algorithm header.
In this example,
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
// Define a vector containing elements
std::vector<int> vec = {1, 2, 3, 4, 5};
// Specify the number of positions to rotate the items to the left
int rotate_by = 2;
// Rotate the items to the left by the specified number of positions
std::rotate(vec.begin(), vec.begin() + rotate_by, vec.end());
// Print the rotated vector
std::cout << "[ ";
for (int i : vec) {
std::cout << i << " ";
}
std::cout << "]" << std::endl;
return 0;
}
[3 4 5 1 2]
In this example,
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
// Define a vector containing elements
std::vector<int> vec = {1, 2, 3, 4, 5};
// Specify the number of positions to rotate the items to the right
int rotate_by = 2;
// Rotate the items to the right by the specified number of positions
std::rotate(vec.rbegin(), vec.rbegin() + rotate_by, vec.rend());
// Print the rotated vector
std::cout << "[ ";
for (int i : vec) {
std::cout << i << " ";
}
std::cout << "]" << std::endl;
return 0;
}
[4 5 1 2 3]
In this tutorial, we learned How to Rotate Items in a Vector in C++ language with well detailed examples.