我正在遍歷一個向量,向量中的每個條目都必須根據條目寫入檔案。
假設向量 {檔案 A,檔案 B,檔案 C,檔案 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));
uj5u.com熱心網友回復:
C 流類是不可復制的,但是您在構建std::pairfor時嘗試進行復制insert()。這就是代碼無法編譯的原因。
您必須std::ofstream直接在地圖內構造物件,或者至少使用移動語意將所有權轉移到地圖中,例如:
std::map<std::string, std::ofstream> filemap;
std::vector<std::string> items;
...
for (const auto &filename : items) {
auto iter = filemap.find(filename);
if (iter == filemap.end()) {
iter = filemap.emplace(filename, filename).first;
// or:
// iter = filemap.emplace(make_pair(filename, ofstream(filename))).first;
// or:
// std::ofstream ofs(filename);
// iter = filemap.insert(std::make_pair(filename, std::move(ofs))).first;
}
iter->second << key.first << "-" << key.second << std::endl;
}
或者,讓std::map默認std::ofstream為您構建物件,然后您可以open()在需要時使用它們,例如:
std::map<std::string, std::ofstream> filemap;
std::vector<std::string> items;
...
for (const auto &filename : items) {
auto &ofs = filemap[filename];
if (!ofs.is_open()) {
ofs.open(filename);
}
ofs << key.first << "-" << key.second << std::endl;
}
uj5u.com熱心網友回復:
這可能是您想要實作的目標嗎?:
#include <fstream>
#include <string>
#include <unordered_map>
int main()
{
std::unordered_map<std::string, std::ios_base::openmode> fname_to_fstream_pairs = {{"vacation.png", std::ofstream::out}, {"diary.txt", std::ofstream::in}};
auto const& fname_to_fstream_pair = fname_to_fstream_pairs.find("vacation.png");
if (fname_to_fstream_pair != std::end(fname_to_fstream_pairs))
{
std::ofstream ofs(fname_to_fstream_pair->first, fname_to_fstream_pair->second);
ofs << "The vacation was great!";
}
return 0;
}
std::end表示超出容器末尾的元素。所以,通常it == std::end(v)不是你想要的。
PS:哦,你不應該那樣寫照片。那只是一個愚蠢的例子。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/365027.html
