简体   繁体   中英

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

I am trying to read 2000 key and value pairs from a file and store them into a unordered_map. Currently it seems to work, the only thing is that it only stores the last 200 or so into the map. I am thinking that the key and items are being overwriten because the map is not rehashing or something along those lines.

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

My guess is that you have double keys in your source data. If this is the case, then you have chosen the wrong container type.

If you want to store all values distinct, then you should use a std::unordered_multimap or a std::multimap. But then you could also use a std::vector<std::pair<std::string,std::string>> .

Again a guess, you want to store keys and all found values for this key. Then you need to use a std::unordered_map<std::string,std::vector<std::string>> . For adding values, you would write

 myMap[key].push_back[item];

and for the output something like

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";
}

Please check. As said, many guesses . . .

(All code is uncompiled and untested)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM