【问题标题】:Converting ruby hash into c++ map将 ruby​​ 哈希转换为 C++ 映射
【发布时间】:2011-12-10 20:50:48
【问题描述】:

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

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

【问题讨论】:

    标签: c++ ruby hash map


    【解决方案1】:

    只需使用纯简格式的输入:

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

    【讨论】:

    • 如果字符串包含空格,这将失败:a string with spaces =&gt; 1 2 3
    • @DavidRodríguez-dribeas:确实如此。如果需要,请将第一个输入操作替换为等待=&gt; 的循环,或使用substr() 来定位分隔符。欢迎 OP 澄清是否需要这样做。
    • 字符串不会有任何空格,但可以是作为字符串有效的数字。谢谢
    【解决方案2】:

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

    #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&lt;int&gt; 将尝试从文件中读取整数,直到发生错误(例如无法转换为整数的字符)或到达流的末尾
    • input.clear() 清除流中的所有错误(上面的std::copy 总是以错误结尾)
    • 如果您的键可以被解析为整数或包含空格,则此解决方案将无法正常工作

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

    【讨论】:

    • 如果字符串包含空格,这将失败,如果数字作为字符串有效,它也会失败,例如:10 =&gt; 1 2 3 4 5。 “10”是一个有效的字符串,也是一个有效的数字。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-05
    • 2011-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-08
    • 1970-01-01
    相关资源
    最近更新 更多