To reverse a list in C++ using std::list, you can use the reverse
function from the
header.
In this example,
originalList
containing elements in the original order.std::reverse
function to reverse the list.#include <iostream>
#include <list>
#include <algorithm>
int main() {
std::list<int> originalList = {1, 2, 3, 4, 5};
std::reverse(originalList.begin(), originalList.end());
std::cout << "Reversed list:";
for (int num : originalList) {
std::cout << " " << num;
}
return 0;
}
Reversed list: 5 4 3 2 1
In this example,
originalList
.std::reverse
function to reverse the list.#include <iostream>
#include <list>
#include <algorithm>
int main() {
std::list<std::string> originalList = {"apple", "banana", "orange", "grape"};
std::reverse(originalList.begin(), originalList.end());
std::cout << "Reversed list:";
for (const std::string& fruit : originalList) {
std::cout << " " << fruit;
}
return 0;
}
Reversed list: grape orange banana apple
In this tutorial, we learned How to Reverse a List in C++ language with well detailed examples.