2011-10-19 43 views
1

有沒有辦法將紅寶石中產生的散列轉換爲C++映射?我已經嘗試將散列打印到文件中,但不知道如何將其讀入C++映射。將紅寶石散列轉換爲C++映射

散列被印刷以下述方式:

stringA => 123 234 345 456 567 
stringB => 12 54 103 313 567 2340 
... 

號碼的量爲每個相關聯的串而變化,和琴絃都是唯一的。我想用:

std::map<std::string,std::vector<unsigned int>> stringMap; 

如何分別讀取每行的字符串和數組部分?

回答

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 
} 
+0

如果字符串中包含空格,則會失敗:'帶空格的字符串=> 1 2 3' –

+0

@DavidRodríguez-dribeas:的確如此。如果需要,可以用等待'=>'的循環替換第一個輸入操作,或者使用'substr()'來定位分隔符。 OP歡迎澄清這是否是必需的。 –

+0

該字符串不會有任何空格,但可以是一個有效的數字作爲字符串。謝謝 – zanbri

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 wi永遠都會在一個錯誤結尾)
  • 預期,如果你的鑰匙,可以作爲整數來分析這個解決方案將無法正常工作,或者如果它們包含空格

如果這些限制是嚴格的你,你可以看看Boost.Spirit.Qi

+1

如果字符串包含空格,這將失敗,如果數字有效爲字符串,它也會失敗,如:'10 => 1 2 3 4 5'。 「10」是一個有效的字符串,但也是一個有效的數字。 –