c++ - How to print the multimap elements having vector? -
i have created multimap.
multimap<int, std::vector<string> > mt;.
also have inserted elements using:
mt.insert(std::make_pair(threadid, funcname));
how print elements in multimap using key , value pair?
you can overwrite operator<< vector , multimap. printing code looked easier:
#include <iostream> #include <map> #include <vector> #include <string> template< class t > std::ostream & operator << ( std::ostream & os, const std::vector< t > & v ) { ( const auto & : v ) { os << << std::endl; } return os; } template< class k, class v > std::ostream & operator << ( std::ostream & os, const std::multimap< k, v > & m ) { ( const auto & : m ) { os << i.first << " : " << std::endl; os << i.second << std::endl; } return os; } int main() { std::multimap<int, std::vector< std::string > > m; m.insert(std::make_pair( 1, std::vector< std::string >( {"one", "two", "three" } ) ) ); m.insert(std::make_pair( 10, std::vector< std::string >( {"ten", "twenty", "thirty" } ) ) ); m.insert(std::make_pair( 42, std::vector< std::string >( {"foutry", "two" } ) ) ); std::cout << m; } if don't want overwrite operator << (i'm wondering why...) can in place:
int main() { std::multimap<int, std::vector< std::string > > m; m.insert(std::make_pair( 1, std::vector< std::string >( {"one", "two", "three" } ) ) ); m.insert(std::make_pair( 10, std::vector< std::string >( {"ten", "twenty", "thirty" } ) ) ); m.insert(std::make_pair( 42, std::vector< std::string >( {"foutry", "two" } ) ) ); ( const auto & : m ) { std::cout << i.first << " : " << std::endl; ( const auto & i_v : i.second ) { std::cout << i_v << std::endl; } } } at last, if can't use c++11 (i'm wondering why...) can change code this:
int main() { typedef std::vector< std::string > strings_t; typedef std::multimap<int, strings_t > map_t; map_t m; { strings_t v; v.push_back( "one" ); v.push_back( "two" ); v.push_back( "three" ); m.insert( std::make_pair( 1, v ) ); } { strings_t v; v.push_back( "ten" ); v.push_back( "twenty" ); v.push_back( "thirty" ); m.insert( std::make_pair( 10, v ) ); } { strings_t v; v.push_back( "foutry" ); v.push_back( "two" ); m.insert( std::make_pair( 42, v ) ); } ( map_t::const_iterator = m.begin(), e = m.end(); != e; ++i ) { std::cout << i->first << " : " << std::endl; ( strings_t::const_iterator i_v = i->second.begin(), e_v = i->second.end(); i_v != e_v; ++i_v ) { std::cout << (*i_v) << std::endl; } } }
Comments
Post a Comment