To rotate elements in a list in C++ using std::list, you can use std::rotate algorithm from the
In this example,
numbers
with integer values using std::list.#include <iostream>
#include <list>
#include <algorithm>
int main() {
std::list<int> numbers = {1, 2, 3, 4, 5};
int distance = 2;
std::rotate(numbers.begin(), numbers.begin() + distance, numbers.end());
for (int num : numbers) {
std::cout << num << " ";
}
return 0;
}
Rotated list: 3 4 5 1 2
In this example,
words
with string values using std::list.#include <iostream>
#include <list>
#include <algorithm>
#include <string>
int main() {
std::list<std::string> words = {"apple", "banana", "cherry", "date", "elderberry"};
int distance = 3;
std::rotate(words.begin(), words.begin() + distance, words.end());
for (const std::string& word : words) {
std::cout << word << " ";
}
return 0;
}
Rotated list: date elderberry apple banana cherry
In this tutorial, we learned How to Rotate Elements in a List in C++ language with well detailed examples.