load std::map from text file

前端 未结 2 1294
孤独总比滥情好
孤独总比滥情好 2021-01-05 11:02

This is a very simple thing, so I want to keep it as simple as it sounds. All I want is to load a bunch of key-value paires from a file, and populate them in to a map. I do

2条回答
  •  醉梦人生
    2021-01-05 11:11

    Since you seem to want the simplest thing humanly possible, I'm going to suggest something incredibly simple that may or may not work based on your map contents. If your map data values are strings that include spaces, this wont work. If they're strings without spaces, or numeric, you're set.

    This isn't tested code, but it's close and simple so you should be fine even if it doesn't quite compile. Just change KeyType and ValueType to int, string, float, or whatever you're actually using in the file.

    Set up file like:

    key value
    key2 value2
    key3 value3
    key4 value4
    

    Read like:

    KeyType key;
    ValueType value;
    
    std::map myMap;
    while (infile >> key >> value)
        myMap[key] = value;
    

提交回复
热议问题