We help IT Professionals succeed at work.

Question about the class type <list>

50256880
50256880 asked
on
How to print the nodes and the whole list out in <list>?
Comment
Watch Question

CERTIFIED EXPERT
Commented:
Hi 50256880,

don't know what you mean with 'nodes and the
whole list', but maybe you mean something like
this:

// i.e. list of ints
#include <list>
#include <iostream>

std::list<int> list;
std::list<int>::iterator i;

// fill list with some values
list.push_back( 6 );
list.push_back( 2 );
list.push_back( 9 );
list.push_back( 23 );
list.push_back( 1 );
list.push_back( 77 );
list.push_back( 34 );

int cnt = 0; // just a counter
for ( i = list.begin(); i != list.end(); i++ )
 std::cout << "Element Nr. " << ++cnt << " = " << *i << std::endl;

this produces output like:
Element Nr. 1 = 6
Element Nr. 2 = 2
Element Nr. 3 = 9
Element Nr. 4 = 23
Element Nr. 5 = 1
Element Nr. 6 = 77
Element Nr. 7 = 34


hope that helps,

ZOPPO
list<int> li;
....
copy(li.begin(), li.end(), ostream_iterator<int>(cout));

//or

ofstream f("output.file");
copy(li.begin(), li.end(), ostream_iterator<int>(f));

// or

ostringfstream oss;
copy(li.begin(), li.end(), ostream_iterator<int>(oss));
string s = oss.str();



AxterSenior Software Engineer

Commented:
The following function will print out any STL container of any standard type, to the screen.

template<class T>
PrintMyContainer(const T &Container)
{
     std::copy(Container.begin(), Container.end(), std::ostream_iterator<T::value_type>(std::cout));
}

This function uses the same methods that AssafLavie's code uses.

Explore More ContentExplore courses, solutions, and other research materials related to this topic.