c# - 将数据解析为 C++ 二维 map

标签 c# c++ csv

我想使用 C++ 将 csv 文件解析为二维 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++ 中做完全相同的事情?

最佳答案

#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;
}

关于c# - 将数据解析为 C++ 二维 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34039769/

相关文章:

c# - 数据库的跨平台加密

c++ - 为您的程序添加类似 C/C++ 的预处理能力

c++ - 使用 C++ 文件处理从文件中读取异常错误

c - 在没有表模式的情况下将 CSV 导入 SQLite

c# - 关于如何使用 UpdateSourceTrigger=Explicit 和 MVVM 的一个很好的例子

c# - 当我尝试在 VS 中添加文件时加载类型库/DLL 时出错(HRESULT : 0x80029C4A)

r - XPT转换为CSV?

python - 将 csv 的每一行导出到单独的文本文件中显示关键错误

c# - 加载到 richtextbox wpf c# 后,rtf 布局发生了变化

c++ - 三角矩阵转换和自动并行化