将ruby哈希转换为c ++ map

时间:2011-10-19 11:40:46

标签: c++ ruby hash map

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

如何分别读取每一行的字符串和数组部分?

2 个答案:

答案 0 :(得分:1)

只需使用普通的Jane格式输入:

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

答案 1 :(得分:0)

是的,这是可能的。一个简单的解决方案可能如下所示:

#include <fstream>
#include <iterator>
#include <string>
#include <map>
#include <vector>
#include <algorithm>

int main() {
    std::ifstream input("your_file.txt");
    std::map<std::string,std::vector<unsigned int>> stringMap;
    std::string key, dummy; // dummy is for eating the "=>"
    while(input >> key >> dummy) {
        std::copy(std::istream_iterator<int>(input), 
                  std::istream_iterator<int>(),
                  std::back_inserter(stringMap[key]));
        input.clear();
    }
}

一些注意事项:

  • stringMap[key]将在地图中创建新条目(如果不存在)
  • std::istream_iterator<int>将尝试从文件中读取整数,直到发生错误(例如无法转换为整数的字符),或者到达流的末尾
  • input.clear()清除流中的所有错误(上面的std::copy将始终以错误结束)
  • 如果您的密钥可以解析为整数,或者如果它们包含空格,则此解决方案将无法正常工作

如果这些限制对你很严格,你可以查看Boost.Spirit.Qi

相关问题