我有一张由以下人员定义的地图:
map < char, vector < unsigned char>> dict;
函数生成并将内容添加到此字典后,我想接下来遍历并打印循环中的每个键:值对。
for(auto it = dict.begin(); it != dict.end(); ++it)
{
cout << it.first << " : ";
// how to output the vector here? since the len of value differs
// for each key I need that size
for( unsigned int s = it.size()
}
如何从迭代器中获取值的大小,以便我可以迭代它的向量来输出它。
答案 0 :(得分:3)
我知道这个问题有点陈旧,但我有一个类似的问题,这篇文章帮助了我,所以我想我可以在这里发布我的解决方案。
基于此处的示例:map and multimap
我有map
一对<string, vector<string> >
,其中vector<string>
当然会包含多个值
#include <string.h>
#include <iostream>
#include <map>
#include <utility>
#include <vector>
using namespace std;
int main() {
map< string, vector<string> > Employees;
vector <string> myVec;
string val1, val2, val3;
val1 = "valor1";
val2 = "valor2";
val3 = "valor3";
// Examples of assigning Map container contents
// 1) Assignment using array index notation
Employees["Mike C."] = {"val1","val2", "val3"};
Employees["Charlie M."] = {"val1","val2", "val3"};
// 2) Assignment using member function insert() and STL pair
Employees.insert(std::pair<string,vector<string> >("David D.",{val1,val2,val3}));
// 3) Assignment using member function insert() and "value_type()"
Employees.insert(map<string,vector<string> >::value_type("John A.",{"val7","val8", "val9"}));
// 4) Assignment using member function insert() and "make_pair()"
myVec.push_back("val4");
myVec.push_back(val1);
myVec.push_back("val6");
Employees.insert(std::make_pair("Peter Q.",myVec));
cout << "Map size: " << Employees.size() << endl;
for(map<string, vector<string> >::iterator ii=Employees.begin(); ii!=Employees.end(); ++ii){
cout << (*ii).first << ": ";
vector <string> inVect = (*ii).second;
for (unsigned j=0; j<inVect.size(); j++){
cout << inVect[j] << " ";
}
cout << endl;
}
}
您可能会注意到添加信息的不同方法,以及打印对的打印部分&#34; key-vector&#34; vector有几个值。 如果是C ++ 11:
,我们也可以这样打印for(auto ii=Employees.begin(); ii!=Employees.end(); ++ii){
cout << (*ii).first << ": ";
vector <string> inVect = (*ii).second;
for (unsigned j=0; j<inVect.size(); j++){
cout << inVect[j] << " ";
}
cout << endl;
}
输出如下:
Map size: 5
Charlie M.: val1 val2 val3
David D.: valor1 aVal1 valor3
John A.: val7 val8 val9
Mike C.: val1 val2 val3
Peter Q.: val4 valor1 val6
P.S。:我不知道为什么输出的顺序不同,我相信不同的推送方法及其速度与它有关。
答案 1 :(得分:2)
it.second
将为您提供给定地图元素的矢量副本,以便您可以将内部循环更改为
for(auto it2 = it.second.begin(); it2 != it.second.end(); ++it2)
cout << *it2 << " ";
答案 2 :(得分:1)
在C ++ 11中,你可以这样做:
for(auto mapIt = begin(dict); mapIt != end(dict); ++mapIt)
{
std::cout << mapIt->first << " : ";
for(auto c : mapIt->second)
{
std::cout << c << " ";
}
std::cout << std::endl;
}
注意非成员的开始/结束。另外,如果你不需要ostream刷新,当然要扔掉std::endl
。
答案 3 :(得分:0)