从 CSV 文件中Unordered_map值
Unordered_map values from CSV file
我找到了一个我正在尝试实现的类似示例:
std::unordered_map<std::string,std::string> mymap = {
{"us","United States"},
{"uk","United Kingdom"},
{"fr","France"},
{"de","Germany"}
};
但是,我拥有的值在 CSV 文件中。
我是否需要将这些值插入到不同的容器中,然后将它们添加到unordered_map中,或者是否可以直接从文件添加它们?
我正在努力弄清楚,所以目前我只是将文件内容写到屏幕上:
int menuLoop = 1;
int userChoice;
string getInput;
while(menuLoop == 1)
{
cout << "Menunn"
<< "1. 20n"
<< "2. 100n"
<< "3. 500n"
<< "4. 1000n"
<< "5. 10,000n"
<< "6. 50,000nn";
cin >> userChoice;
if(userChoice == 1)
{
cout << "n20nn";
string getContent;
ifstream openFile("20.txt");
if(openFile.is_open())
{
while(!openFile.eof())
{
getline(openFile, getContent);
cout << getContent << endl;
}
}
system("PAUSE");
}
}
文件的内容:
Bpgvjdfj,Bvfbyfzc
Zjmvxouu,Fsmotsaa
Xocbwmnd,Fcdlnmhb
Fsmotsaa,Zexyegma
Bvfbyfzc,Qkignteu
Uysmwjdb,Wzujllbk
Fwhbryyz,Byoifnrp
Klqljfrk,Bpgvjdfj
Qkignteu,Wgqtalnh
Wgqtalnh,Coyuhnbx
Sgtgyldw,Fwhbryyz
Coyuhnbx,Zjmvxouu
Zvjxfwkx,Sgtgyldw
Czeagvnj,Uysmwjdb
Oljgjisa,Dffkuztu
Zexyegma,Zvjxfwkx
Fcdlnmhb,Klqljfrk
Wzujllbk,Oljgjisa
Byoifnrp,Czeagvnj
要提取数据,请使用 CSV 解析器库或使用逗号作为分隔符手动拆分文件的每一行。CSV 文件与文本文件没有什么不同;它们只是遵循独特的数据格式。
中间数据结构是不必要的。假设您的数据采用 [key],[value]
格式,请使用此处unordered_map的C++文档正确插入数据。
例:
string line;
getline(file, line);
// simple split (alternatively, use strtok)
string key = line.substr(0,line.find(','));
string value = line.substr(line.find(',')+1);
unordered_map<string,string> mymap;
mymap[key] = value;
编辑:us2012 带有分隔符的 getline 方法也特别有用。还要记住,在读取带有分隔符的 CSV 作为数据时必须注意,通常由用引号括起来的值表示:
"hello, world","hola","mundo"
有关 CSV 格式的更多信息,请参阅此处。
可以直接在 getline
中指定分隔符。
while(true)
{
string key, value;
//try to read key, if there is none, break
if (!getline(openFile, key, ',')) break;
//read value
getline(openFile, value, 'n');
mymap[key] = value;
cout << key << ":" << value << endl;
}
请注意,当前循环检查您是否在文件末尾太晚,并且将生成空键,值对。这在上面得到了纠正。
相关文章:
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- 使用一个考虑到std::map中键值的滚动或换行的键
- 为什么 const std::p air<K,V>& 在 std::map 上基于范围的 for 循环不起作用?
- 允许从 std::map 的密钥窃取资源?
- 有没有办法对std::unordered_set、std::unrdered_map、std::set、std::map
- 将重物插入std::map
- 使用通用值初始化 std::map,不重复
- 仅包含可移动 std::map 的类的移动构造函数不起作用
- C++:当所有条目都保证是唯一时,替代 std::map
- 使用模板化的键类型定义 std::map,该键类型基于作为参数接收的函数
- 如果 KEY 是 std::list 或 std::vector 而不是值,那么 std::map 的默认行为是什么?
- 使用字符数组作为 Map 中的键
- C++如何创建 std::map
- C++ equivalent to Java Map getOrDefault?
- 从其他容器中移动构造"std::map"
- 如何使用 uint64_t 键类型从 std::map<int, std::string> 返回值?
- 将 std::map::emplace 与返回 shared_ptr 的函数一起使用是否正确?
- C++中 std::map 的运行时复杂度是多少?
- unordered map -在c++ std::unordered_map中预分配桶