我在加载和打印 map-map-vector 数据结构时遇到问题。我认为它在打印方面,因为我不是 100% 确定如何使用迭代器。
我创建数据并将其加载到结构中以在此处存储我的数据: (我创建了 inner_test 和 myvector,因为看起来我需要它们用于迭代器。我不确定迭代器如何知道 inner_test 和 myvector 是测试的一部分。)
map<int, map<string, vector<string>>> test;
map<string, vector<string>> inner_test;
vector<string> myvector;
ifstream thisfile;
const char *file1 = argv[1];
thisfile.open(file1);
string filler;
while( thisfile >> filler ){
string sortedFiller = filler;
sort(sortedFiller.begin(), sortedFiller.end());
test[filler.length()][sortedFiller].push_back(filler);
}
thisfile.close();
我试着用这个打印它,但我觉得我不太明白我在这里做什么。
map<int, map<string, vector<string>>>::iterator itr1;
map<string, vector<string>>::iterator itr2;
vector<string>::iterator itr3;
for(itr1 = test.begin(); itr1 != test.end(); itr1++){
cout << itr1->first;
for(itr2 = inner_test.begin(); itr2 != inner_test.end(); itr2++){
cout << itr2->first;
for(itr3 = myVector.begin(); itr3 != myVector.end(); itr3++){
cout << *itr3;
}
}
cout << endl;
}
最佳答案
你的 inner_test
和 my_vector
变量是空容器,与实际的 std::map
无关,你想打印,以任何方式。这是如何打印多维容器的示例之一:
// auto type automatically defines itself as a return type of test.begin ()
for(auto itr1 = test.begin(); itr1 != test.end(); itr1++)
{
cout << itr1->first << ' '; // Add space to separate entries on the same line
// itr1->second represents map<string, vector<string>> stored in test.
for(auto itr2 = itr1->second.begin (); itr2 != itr1->second.end (); itr2++)
{
cout << itr2->first << ' ';
// itr2->second represents vector<string> stored in map<string, vector<string>> which is stored in test.
for(auto itr3 = itr2->second.begin(); itr3 != itr2->second.end(); itr3++)
{
cout << *itr3 << ' ';
}
}
cout << endl;
}
关于c++ - 如何打印嵌套的 map - map - vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40656802/