我需要同时写一堆文件,所以我决定使用map <string, ofstream>.
map<string, ofstream> MyFileMap;
Run Code Online (Sandbox Code Playgroud)
我拿了一个vector<string> FileInd,包括,说"a" "b" "c",并尝试打开我的文件:
for (vector<string>::iterator it = FileInd.begin(); iter != FileInd.end(); ++it){
...
MyFileMap[*it].open("/myhomefolder/"+(*it)+".");
}
Run Code Online (Sandbox Code Playgroud)
我收到了错误
request for member 'open' in ..... , which is of non-class type 'std::ofstream*'
Run Code Online (Sandbox Code Playgroud)
我试过切换到
map<string, ofstream*> MyFileMap;
Run Code Online (Sandbox Code Playgroud)
但它也没有用.
有人可以帮忙吗?
谢谢.
澄清:
我试过了两个
map<string, ofstream> MyFileMap;
map<string, ofstream*> MyFileMap;
既
.open
->open
4种变体都不起作用.
解决方案(在Rob的代码中建议):
基本上,我忘了"新",以下为我工作:
map<string, ofstream*> MyFileMap;
MyFileMap[*it] = new ofstream("/myhomefolder/"+(*it)+".");
Run Code Online (Sandbox Code Playgroud)
Rob*_*obᵩ 10
std::map<std::string, std::ofstream>不可能工作,因为std::map要求其数据类型为可分配,而std::ofstream不是.在替代方案中,数据类型必须是指向ofstream的指针 - 原始指针或智能指针.
以下是我将如何使用C++ 11的功能:
#include <string>
#include <map>
#include <fstream>
#include <iostream>
#include <vector>
int main (int ac, char **av)
{
// Convenient access to argument array
std::vector<std::string> fileNames(av+1, av+ac);
// If I were smart, this would be std::shared_ptr or something
std::map<std::string, std::ofstream*> fileMap;
// Open all of the files
for(auto& fileName : fileNames) {
fileMap[fileName] = new std::ofstream("/tmp/xxx/"+fileName+".txt");
if(!fileMap[fileName] || !*fileMap[fileName])
perror(fileName.c_str());
}
// Write some data to all of the files
for(auto& pair : fileMap) {
*pair.second << "Hello, world\n";
}
// Close all of the files
// If I had used std::shared_ptr, I could skip this step
for(auto& pair : fileMap) {
delete pair.second;
pair.second = 0;
}
}
Run Code Online (Sandbox Code Playgroud)
和第二节,在C++ 03中:
#include <string>
#include <map>
#include <fstream>
#include <iostream>
#include <vector>
int main (int ac, char **av)
{
typedef std::map<std::string, std::ofstream*> Map;
typedef Map::iterator Iterator;
Map fileMap;
// Open all of the files
std::string xxx("/tmp/xxx/");
while(av++,--ac) {
fileMap[*av] = new std::ofstream( (xxx+*av+".txt").c_str() );
if(!fileMap[*av] || !*fileMap[*av])
perror(*av);
}
// Write some data to all of the files
for(Iterator it = fileMap.begin(); it != fileMap.end(); ++it) {
*(it->second) << "Hello, world\n";
}
// Close all of the files
for(Iterator it = fileMap.begin(); it != fileMap.end(); ++it) {
delete it->second;
it->second = 0;
}
}
Run Code Online (Sandbox Code Playgroud)