读取文本文件并将其内容存储在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
}
}
}
您在错误的地方有内部环(并且根本不需要它)。
首先在简单的输入操作中获取"键"。然后读取所有整数并将它们添加到向量。最后,读取了该行的所有数据之后,您将键和值(向量)添加到地图。
。类似的东西:
// 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;
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- .cpp和.h文件中的模板专用化声明
- 反向给定链表中的K节点
- 正在查找文档以获得PS4平台的C++中的设备信息
- enum是C++中的宏变量还是整数变量
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 将字符串存储在c++中的稳定内存中
- 文本文件中的单词链表
- 递归函数计算序列中的平方和(并输出过程)
- 如何从C++中的依赖类型中获得它所依赖的类型
- C++中的"inline"关键字
- 如何运行位于boost/libs/python/example/tutorial目录中的hello.cpp和Jamfil
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 用C++中的一个变量定义一个常量
- vector.resize()中的分配错误
- 使用指针从C++中的数组中获取最大值
- arr[-1]在c++中的奇怪行为
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 将值指定给向量(2D)的向量中的某个位置
- 内置函数可查看CPP中的成员变量