簡體   English   中英

將文件內容存儲到 unordered_map 僅存儲最后的項目和值

[英]Storing file contents to unordered_map only storing the last items and values

我正在嘗試從文件中讀取 2000 個鍵和值對並將它們存儲到 unordered_map 中。 目前它似乎有效,唯一的問題是它只將最后 200 個左右存儲到地圖中。 我認為密鑰和項目正在被覆蓋,因為地圖沒有重新散列或沿着這些路線的東西。

std::unordered_map<std::string, std::string> myMap;

std::ifstream infile;
infile.open("Text3m.txt");

std::string key;
std::string item;

if (infile.is_open())
{
    std::string line;
    while (std::getline(infile, line))
    {
        std::stringstream ss(line);

        std::getline(ss, key, ',');
        std::getline(ss, item);

        myMap[key] = item;

        //std::cout << key << ", " << item << std::endl;

        //std::cout << key << ", " << item << std::endl;

    }


}

for (auto const& n : myMap)
{
    std::cout << n.first << ", " << n.second << std::endl;
}

我的猜測是您的源數據中有雙鍵。 如果是這種情況,那么您選擇了錯誤的容器類型。

如果要存儲所有不同的值,則應使用std::unordered_multimap或 std::multimap。 但是你也可以使用std::vector<std::pair<std::string,std::string>>

再次猜測,您想要存儲該鍵的鍵和所有找到的值。 然后你需要使用std::unordered_map<std::string,std::vector<std::string>> 為了添加值,你會寫

 myMap[key].push_back[item];

和輸出類似

for (auto const& n : myMap)
{
    std::cout << n.first << " --> " ;
    std::copy(n.second.begin(),n.second.end(),std::ostream_iterator<std::string>(std::cout," "));
    std::cout << "\n";
}

請檢查。 如上所述,許多猜測。 . .

(所有代碼未經編譯和測試)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM