Listing the contents of a list from a C ++ list library

I wanted to print the contents of a list for a simple program that I am writing. I use the built-in list library

#include <list> 

however, I do not know how to print the contents of this list in order to check / verify the data inside. How to do it?

+4
source share
5 answers

If you have a recent compiler (which includes at least a few C ++ 11 functions), you can avoid calling iterators (if you want):

 #include <list> #include <iostream> int main() { list<int> mylist = {0, 1, 2, 3, 4}; for (auto v : mylist) std::cout << v << "\n"; } 
+8
source

Try:

 #include <list> #include <algorithm> #include <iterator> #include <iostream> int main() { list<int> l = {1,2,3,4}; // std::copy copies items using iterators. // The first two define the source iterators [begin,end). In this case from the list. // The last iterator defines the destination where the data will be copied too std::copy(std::begin(l), std::end(l), // In this case the destination iterator is a fancy output iterator // It treats a stream (in this case std::cout) as a place it can put values // So you effectively copy stuff to the output stream. std::ostream_iterator<int>(std::cout, " ")); } 
+5
source

For example, for an int list

 list<int> lst = ...; for (list<int>::iterator i = lst.begin(); i != lst.end(); ++i) cout << *i << endl; 

If you work with a list, you get used to iterators very quickly.

+3
source

You are using an Iterator.

 for(list<type>::iterator iter = list.begin(); iter != list.end(); iter++){ cout<<*iter<<endl; } 
+1
source

You can use iterators and a small for loop to do this. Since you are simply exposing the values ​​in a list, you should use const_iterator and not iterator to prevent accidentally modifying the object referenced by the iterator.

Here is an example of how to iterate over a var variable, which is an int 's list

 for (list<int>::const_iterator it = var.begin(); it != var.end(); ++it) cout << *it << endl; 
+1
source

All Articles