【发布时间】:2023-03-16 21:15:01
【问题描述】:
我正在遍历一个向量,向量中的每个条目都必须根据条目写入文件。
假设向量 {File A, File B, File C, File A....}
因此,打开了多个文件描述符,我将它们存储在 std::map:
键 = 文件名,值 = 文件描述符。请参阅下面的代码。
当在地图中找不到文件名时,我会在地图中插入一对数据(文件名、文件描述符)。编译器抛出错误。在代码后面查看错误详情。
std::map <std::string, std::ofstream> filemap; // maintains filename for each item in the list.
std::vector <std::string> items;
for (i=0 ; i < items.size() ; i++) {
if (keyfilemap.find(items[i]) == keyfilemap.end()) {
std::ofstream ofs (items(i), std::ofstream::out);
ofs << key.first << "-" << key.second << std::endl;
// **Compiler throws an error here.**
keyfilemap.insert(std::make_pair(filename, ofs));
}
else
keyfilemap[filename] << key.first << "-" << key.second << std::endl;
}
编译器错误。
/usr/include/c++/7/bits/stl_pair.h:529:14: error: no matching function for call to 'std::pair<std::__cxx11::basic_string<char>, std::basic_ofstream<char> >::pair(std::__cxx11::basic_string<char>&, std::basic_ofstream<char>&)'
return __pair_type(std::forward<_T1>(__x), std::forward<_T2>(__y));
【问题讨论】:
-
请提供minimal reproducible example。当前代码似乎不完整,存在未定义符号错误。
-
std::make_pair(filename, ofs)创建ofs的副本。如前所述,不能复制。 -
您在上面的代码中有文件名。 items[i], items(ii) 和 filename...哪个是正确的?
-
如何使用移动?我在下面尝试过,但没有成功。
-
keyfilemap.insert(std::move(std::make_pair(filename, ofs)));