c++ - 将 ruby​​ 哈希转换为 c++ 映射

标签 c++ ruby hash dictionary

有没有办法将用 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/

相关文章:

c++ - 数组作为映射键

ruby-on-rails - Resque-web 界面不工作

ruby - 关于覆盖初始化方法的问题

ruby - 在模块中使用 self

algorithm - 可变大小 bool 数组的哈希算法

ruby - 如何覆盖 Hash native 括号([] 访问)

c++ - 为什么libeay32中SHA512函数的符号没有前导下划线?

c++ - 在仿真器中使用 union 来模拟 CPU 寄存器有多合适?

复杂继承中的 C++ 模板

Java - 从 HashMap 键创建排列