how to print list in c++
To print a list in C++, you can use a range-based for loop or an iterator-based loop. Here's an example of how to do it:
#include <iostream>
#include <list>
int main() {
std::list<int> myList = {1, 2, 3, 4, 5};
// Using a range-based for loop
for (const auto& element : myList) {
std::cout << element << " ";
}
std::cout << std::endl;
// Using an iterator-based loop
for (auto it = myList.begin(); it != myList.end(); ++it) {
std::cout << *it << " ";
}
std::cout << std::endl;
return 0;
}
Explanation:
First, you need to include the necessary headers:
<iostream>
for input/output operations and<list>
for using the list container.Create a list
myList
with some elements. In this example, we have a list of integers with values 1, 2, 3, 4, and 5.Use a range-based for loop to iterate over the elements in the list. The loop variable
element
will take each element of the list in each iteration. Inside the loop, you can print each element usingstd::cout
.Use an iterator-based loop to achieve the same result. In this case, you initialize an iterator
it
withmyList.begin()
to point to the first element of the list. The loop conditionit != myList.end()
checks if the iterator has reached the end of the list. Inside the loop, you can print the element pointed by the iterator using*it
.Finally, use
std::endl
to insert a newline after printing all the elements of the list.Return 0 to indicate successful execution of the program.
This code will output:
1 2 3 4 5
1 2 3 4 5
The first line is the result of the range-based for loop, and the second line is the result of the iterator-based loop. Both loops achieve the same result of printing each element of the list.