printing list elements

S

sam

Hi,

I use "list" data container from STL.
I m wondering how to print out all items from a list thru its iterator?
I currently use two "for loop" for each list:

list<HashMap>::iterator l_iter;
HashMap::iterator m_iter;
for (l_iter=macro_list.begin(); l_iter!=macro_list.end(); l_iter++) {
for (m_iter=l_iter->begin(); m_iter!=l_iter->end(); m_iter++) {
cout << m_iter->first << endl;
}
}
}

Is there any other better way can handle this treversal better?

Thanks
Sam
 
T

Thomas Maier-Komor

sam said:
Hi,

I use "list" data container from STL.
I m wondering how to print out all items from a list thru its iterator?
I currently use two "for loop" for each list:

list<HashMap>::iterator l_iter;
HashMap::iterator m_iter;
for (l_iter=macro_list.begin(); l_iter!=macro_list.end(); l_iter++) {
for (m_iter=l_iter->begin(); m_iter!=l_iter->end(); m_iter++) {
cout << m_iter->first << endl;
}
}
}

Is there any other better way can handle this treversal better?

Thanks
Sam

what do you mean by "better"?

for enhanced readability and performance one might use for_each. But
this requires to write a Functor - i.e. it is more complicated to
understand and requires more lines of code...

Tom
 
M

m.a.stijnman

sam said:
Hi,

I use "list" data container from STL.
I m wondering how to print out all items from a list thru its iterator?
I currently use two "for loop" for each list:

list<HashMap>::iterator l_iter;
HashMap::iterator m_iter;
for (l_iter=macro_list.begin(); l_iter!=macro_list.end(); l_iter++) {
for (m_iter=l_iter->begin(); m_iter!=l_iter->end(); m_iter++) {
cout << m_iter->first << endl;
}
}
}

Is there any other better way can handle this treversal better?

Thanks
Sam

You can use the std::copy function from the standard library, as
demonstrated in several sources around the net, like this one:

http://www.devx.com/getHelpOn/10MinuteSolution/20410/1954?pf=true

under the header "Dumping a Container". For general traversals, you
might also want to check out std::for_each.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top