使用c++实现构建map嵌套vector的集合
关键在于对 map<…,…>::iterator it 对象的使用
#include <QCoreApplication>
#include <map>
#include <iostream>
#include <vector>
using namespace std;
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
vector<vector<string>> result;
//构建一个二维数组
for(int i = 0;i < 6; i++)
{
vector<string> temp;
int j = i%2;
string XXX = "XXX";
string XXX2 = XXX.append(to_string(i));
string region = "region";
string region2 = region.append(to_string(j));
temp.push_back(to_string(i));
temp.push_back(XXX2);
temp.push_back(to_string(j));
temp.push_back(region2);
result.push_back(temp);
}
//通过二维数组创建一个嵌套map
map<string,vector<string>> result_map;
for(int i = 0;i < result.size();i++)
{
string key = result[i][3];
if(result_map.count(key) == 0)
{
vector<string> result_vec;
result_vec.push_back(result[i][1]);
result_map.insert({result[i][3],result_vec});
}
else
{
map<string,vector<string>>::iterator it = result_map.find(key);
it->second.push_back(result[i][1]);
}
}
return a.exec();
}