我想用C ++将csv文件解析成2D Map。 csv文件如下所示:
xxx,1,2
xxx,3,4
xxx,5,6
yyy,7,8
yyy,9,10
zzz,11,12
zzz,13,14
zzz,15,16
来自C#背景,我可以在C#
中使用几行代码轻松完成 Dictionary<string, Dictionary<double, int>> mainMap = new Dictionary<string, Dictionary<double, int>>();
string[] lines = File.ReadAllLines(@"C:\Users\xxx\Desktop\myFile.csv");
foreach(string line in lines)
{
string[] v = line.Split(',');
if (!mainMap.ContainsKey(v[0]))
mainMap[v[0]] = new Dictionary<double, int>();
mainMap[v[0]][Convert.ToDouble(v[1])] = Convert.ToInt32(v[2]);
}
如何仅使用标准(std)库在C ++中完成相同的操作?
答案 0 :(得分:1)
可以继续(假设标准输入):
#include <iostream>
#include <sstream>
#include <string>
#include <map>
int main(){
std::string line, token;
std::stringstream iss;
std::map<std::string, std::map<double, int>> mainMap;
std::string key1;
double key2;
int val;
while(std::getline(std::cin, line)){
iss.clear();
iss.str(line);
size_t token_id(0);
while(std::getline(iss, token, ',')){
if(token_id == 0){
key1 = token;
}else if(token_id == 1){
key2 = std::stod(token);
}else if(token_id == 2){
val = std::stoi(token);
}
token_id++;
}
mainMap[key1][key2] = val;
}
return 0;
}
当然,应该为输入的有效性添加一些检查......
答案 1 :(得分:1)
#include <string>
#include <vector>
#include <iostream>
#include <sstream>
#include <fstream>
#include <utility>
#include <map>
typedef std::map<double, int> DoubleIntMap;
typedef std::map<std::string, DoubleIntMap> MyMap;
int main()
{
MyMap mainMap;
std::ifstream in("C:/Users/xxx/Desktop/myFile.csv"); // Use forward slashes on Windows too
if(in.good()) {
std::string line;
while(std::getline(in, line)) {
std::string item;
std::vector<std::string> parts;
std::stringstream ss(line);
while(std::getline(ss, item, ',')) {
parts.push_back(item);
}
if(parts.size() == 3){
std::string key = parts[0];
double d = std::stod(parts[1]);
int i = std::stoi(parts[2]);
mainMap[key][d] = i;
}
}
// Extra: print them out
// You can use auto in C++11 instead of MyMap::const_iterator but I prefer the proper type :)
for(MyMap::const_iterator iter = mainMap.begin(); iter != mainMap.end(); ++iter) {
const DoubleIntMap& item = iter->second;
for(DoubleIntMap::const_iterator inner_iter = item.begin(); inner_iter != item.end(); ++inner_iter) {
std::cout << iter->first << " (" << inner_iter->first << ", " << inner_iter->second << ")\n";
}
}
}
return 0;
}