To iterate over a list in C++ using std::list, you can use iterators or range-based for loops.
In this example,
header for using std::list.numbers
with integer elements.#include <iostream>
#include <list>
int main() {
std::list<int> numbers = {10, 20, 30, 40, 50};
for (auto it = numbers.begin(); it != numbers.end(); ++it) {
std::cout << *it << "\n";
}
return 0;
}
10 20 30 40 50
In this example,
header for using std::list.words
with string elements.#include <iostream>
#include <list>
#include <string>
int main() {
std::list<std::string> words = {"hello", "world", "from", "C++"};
for (const auto& word : words) {
std::cout << word << "\n";
}
return 0;
}
hello world from C++
In this tutorial, we learned How to Iterate Over a List with Index in C++ language with well detailed examples.