读取文本文件并将其内容存储在 C++ 中的 unoredered_map 中

reading a text file and store its content in an unoredered_map in c++

我有一个如下所示的文本文件:

car 1 2 3
truck 4 5 8
van 7 8 6 3

我想读取此文件并将其值存储在声明为:

的 unordere_map 中
unordered_map <string , vector<int>> mymap

我想将车辆类型存储为键,而其余数字作为该键向量中的值。

到目前为止我所做的是:

int main()
{
    ifstream file("myfile");    
    string line;
    unordered_map <string, vector<int>> mymap;
    while(std::getline(file, line))
    {
        std::istringstream iss(line);
        std::string token;
        while (iss >> token)
        {
       // I don't know how to store the first token as key while the rest as values
        }
    }  
}

您将内部循环放在了错误的位置(实际上根本不需要它)。

首先在简单的输入操作中得到"key"。然后读取所有 整数 并将它们添加到向量中。最后,在读取该行的所有数据后,您将键和值(向量)添加到映射中。

像这样:

// Get the key
std::string token;
iss >> token;

// Get the integers
std::vector<int> values(std::istream_iterator<int>(iss),
                        std::istream_iterator<int>());
// Or use a plain loop to read integers and add them to the vector one by one

// Add the key and vector to the map
mymap[token] = values;