Вопрос по c++, stl – Как отобразить содержимое карты?
Ну, это зависит от того, как вы хотите их отобразить, но вы всегда можете легко их перебрать:
typedef map<string, list<string>>::const_iterator MapIterator;
for (MapIterator iter = mapex.begin(); iter != mapex.end(); iter++)
{
cout << "Key: " << iter->first << endl << "Values:" << endl;
typedef list<string>::const_iterator ListIterator;
for (ListIterator list_iter = iter->second.begin(); list_iter != iter->second.end(); list_iter++)
cout << " " << *list_iter << endl;
}
Я бы попробовал следующее
void dump_list(const std::list<string>& l) {
for ( std::list<string>::const_iterator it = l.begin(); l != l.end(); l++ ) {
cout << *l << endl;
}
}
void dump_map(const std::map<string, std::list<string>>& map) {
for ( std::map<string,std::list<string>>::const_iterator it = map.begin(); it != map.end(); it++) {
cout << "Key: " << it->first << endl;
cout << "Values" << endl;
dump_list(it->second);
}
expected unqualified-id before '<' token
на первой строке:void dump_list(const std::list<string>& l) {
, Нужно ли что-то включать?
Я думаю, вы хотите сбросить содержимое карты для отладки. Я хотел бы отметить, что в следующем выпуске gdb (версия 7.0) будет встроен интерпретатор python, который будет использоваться gcc libstdc ++ для предоставления stl pretty принтеров. Вот пример для вашего случая
#include <map>
#include <map>
#include <list>
#include <string>
using namespace std;
int main()
{
typedef map<string, list<string> > map_type;
map_type mymap;
list<string> mylist;
mylist.push_back("item 1");
mylist.push_back("item 2");
mymap["foo"] = mylist;
mymap["bar"] = mylist;
return 0; // stopped here
}
что приводит к
(gdb) print mymap
$1 = std::map with 2 elements = {
["bar"] = std::list = {
[0] = "item 1",
[1] = "item 2"
},
["foo"] = std::list = {
[0] = "item 1",
[1] = "item 2"
}
}
Ура!
которая подходит для двух целей:
It works with anymap
.
It allows for using <<
.
Функция
template<class key_t, class value_t>
ostream& operator<<(ostream& os, const map<key_t, value_t>& m) {
for (typename map<key_t, value_t>::const_iterator it = m.begin();
it != m.end(); it++) {
os << "Key: " << it->first << ", Value: " << it->second;
}
return os;
}
cout <<
будет работать с любымmap
для которого<<
определяется дляtypename
skey_t
а такжеvalue_t
, В вашем случае это не определено дляvalue_t
(= list<string>
), поэтому вы также должны определить это.
В похожем духе вы можете использовать
template<class T>
ostream& operator<<(ostream& os, const list<T>& l) {
for (typename list<T>::const_iterator it = l.begin(); it != l.end(); it++) {
os << "\"" << *it << "\", ";
}
return os;
}
Итак, вы можете:
Add these two functions. Add the prototypes where needed. Useusing namespace std;
(or add std::
as needed).
Use, e.g.,
cout << mapex << endl;
cout << li << endl;
Помните, что если есть какой-либо другой жизнеспособный кандидат на<<
Только что определили (что, как я понимаю, нет, иначе вы, скорее всего, не зададите этот вопрос), оно может иметь приоритет над существующими.
<algorithm>
:
void printPair(const pair<string, list<string> > &p)
{
cout << "Key: " << p.first << endl;
copy(p.second.begin(), p.second.end(), ostream_iterator<string>(cout, "\n"));
}
for_each(mapex.begin(), mapex.end(), printPair);
Тестовая программа:
#include <iostream>
#include <map>
#include <list>
#include <iterator>
#include <algorithm>
using namespace std;
void printPair(const pair<string, list<string> > &p)
{
cout << "Key: " << p.first << endl;
copy(p.second.begin(), p.second.end(), ostream_iterator<string>(cout, "\n"));
}
int main()
{
map<string, list<string> > mapex;
list<string> mylist1;
mylist1.push_back("item 1");
mylist1.push_back("item 2");
mapex["foo"] = mylist1;
list<string> mylist2;
mylist2.push_back("item 3");
mylist2.push_back("item 4");
mylist2.push_back("item 5");
mapex["bar"] = mylist2;
for_each(mapex.begin(), mapex.end(), printPair);
}