有没有办法将用 ruby 生成的散列转换为 C++ 映射?我试过将散列打印到文件中,但不知道如何将其读入 C++ 映射。
散列的打印方式如下:
stringA => 123 234 345 456 567
stringB => 12 54 103 313 567 2340
...
每个关联字符串的数字数量各不相同,并且字符串是唯一的。我想使用:
std::map<std::string,std::vector<unsigned int>> stringMap;
如何分别读取每一行的字符串和数组部分?
最佳答案
只需使用纯简格式输入:
#include <unordered_map>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
std::ifstream infile("thefile.txt");
std::string line;
std::unordered_map<std::string, std::vector<int>> v;
while (std::getline(infile, line)
{
std::string key, sep;
int n;
std::istringstream iss(line);
if (!(iss >> key >> sep)) { /* error */ }
if (sep != "=>") { /* error */ }
while (iss >> n) v[key].push_back(n);
// maybe check if you've reached the end of the line and error otherwise
// or maybe add the option to end a line at a comment character
}
关于c++ - 将 ruby 哈希转换为 c++ 映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7820753/