我知道这个问题有点老了,但我有一个类似的问题,这篇文章帮助了我,所以我想我可以在这里发布我的解决方案。根据此处找到的示例: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;
}
}
您可能会注意到添加信息的不同方法,以及打印部分,它打印“键向量”对,其中向量有多个值。如果 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
PS:我不知道为什么输出顺序不同,我相信不同的推送方式和他们的速度有关系。