I wanted to print out the contents of a list for a simple program I'm writing. I'm using the built in list library
#include <list>
however, I've no idea how to print out the contents of this list in order to test/check the data within. How do I do this?
If you have a recent compiler (one that includes at least a few C++11 features), you can avoid dealing with iterators (directly) if you want. For a list of "small" things like int
s, you might do something like this:
#include <list>
#include <iostream>
int main() {
list<int> mylist = {0, 1, 2, 3, 4};
for (auto v : mylist)
std::cout << v << "\n";
}
If the items in the list are larger (specifically, large enough that you'd prefer to avoid copying them), you'd want to use a reference instead of a value in the loop:
for (auto const &v : mylist)
std::cout << v << "\n";
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, " "));
}
For instance, for a list of int
list<int> lst = ...;
for (list<int>::iterator i = lst.begin(); i != lst.end(); ++i)
cout << *i << endl;
If you are working with list you better get used to iterators pretty quickly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With