To rotate elements in an array using C++, you can implement a custom rotation function that shifts elements by a specified number of positions.
In this example,
intVector
containing integers.rotateArray
function that shifts elements by a specified number of positions.#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void rotateArray(vector<int>& array, int positions) {
positions %= array.size();
reverse(array.begin(), array.end());
reverse(array.begin(), array.begin() + positions);
reverse(array.begin() + positions, array.end());
}
int main() {
vector<int> intVector = {1, 2, 3, 4, 5};
int positions = 2;
rotateArray(intVector, positions);
cout << "Rotated Vector: [";
for (int i = 0; i < intVector.size(); i++) {
cout << intVector[i];
if (i != intVector.size() - 1) cout << ", ";
}
cout << "]" << endl;
return 0;
}
Rotated Vector: [4, 5, 1, 2, 3]
In this example,
strVector
containing strings.rotateArray
function that shifts elements by a specified number of positions.#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
void rotateArray(vector<string>& array, int positions) {
positions %= array.size();
reverse(array.begin(), array.end());
reverse(array.begin(), array.begin() + positions);
reverse(array.begin() + positions, array.end());
}
int main() {
vector<string> strVector = {"apple", "banana", "cherry", "date", "fig"};
int positions = 3;
rotateArray(strVector, positions);
cout << "Rotated Vector: [";
for (int i = 0; i < strVector.size(); i++) {
cout << strVector[i];
if (i != strVector.size() - 1) cout << ", ";
}
cout << "]" << endl;
return 0;
}
Rotated Vector: [date, fig, apple, banana, cherry]
In this tutorial, we learned How to Rotate Elements in an Array in C++ language with well detailed examples.