Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

map contains value as a list+how to print in C++

Tags:

c++

I have a map having strings as keys and lists of file names as values. ex: Map(firstDir, list(file1,file2,file3))

I know that by using following code I can print value which is of String

{
    cout << "Key: " << pos->first << endl;
    cout << "Value:" << pos->second << endl;
}

But if pos->second contains a List, how to display?

like image 546
sap Avatar asked Dec 09 '22 13:12

sap


2 Answers

overload operator << for list

std::ostream& operator << (std::ostream& out, std::list<ListElemType> const& lst)
{
   for(std::list<ListElemType>::iterator it = lst.begin(); it != lst.end(); ++it)
   {
       if(it != lst.begin())
          out << /*your delimiter*/;  
       out << *it;
   }
   return out;
}

now you can do what you want

cout << "Key: " << pos->first << endl << "Value:" << pos->second << endl; 
like image 136
Armen Tsirunyan Avatar answered Dec 28 '22 08:12

Armen Tsirunyan


How about using Boost.Foreach ?

#include <boost/foreach.hpp>

{
    cout << "Key: " << pos->first << endl;
    cout << "Values:" << endl;
    BOOST_FOREACH(std::string const& file, pos->second)
    {
      cout << "\t" << file << endl;
    } 
}
like image 40
Benoît Avatar answered Dec 28 '22 07:12

Benoît