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

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

本文关键字:中的 Unoredered map 存储 文件 取文本 读取      更新时间:2023-10-16

我有一个看起来像:

的文本文件
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
        }
    }  
}

您在错误的地方有内部环(并且根本不需要它)。

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

类似的东西:

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