Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing out contents of a list from the c++ list library [duplicate]

Tags:

c++

list

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?

like image 977
Drew L. Facchiano Avatar asked Apr 26 '13 06:04

Drew L. Facchiano


3 Answers

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 ints, 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";
like image 120
Jerry Coffin Avatar answered Nov 09 '22 14:11

Jerry Coffin


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, " "));
}
like image 40
Martin York Avatar answered Nov 09 '22 15:11

Martin York


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.

like image 34
john Avatar answered Nov 09 '22 15:11

john