I need to write to a bunch of files simultaneously, so I decided to use map <string, ofstream>.
map<string, ofstream> MyFileMap;
I take a vector<string> FileInd, which consists of, say "a" "b" "c", and try to open my files with:
for (vector<string>::iterator it = FileInd.begin(); iter != FileInd.end(); ++it){
...
MyFileMap[*it].open("/myhomefolder/"+(*it)+".");
}
I get the error
request for member 'open' in ..... , which is of non-class type 'std::ofstream*'
I’ve tried to switch to
map<string, ofstream*> MyFileMap;
But it didn’t work either.
Could anyone help?
Thanks.
Clarification:
I’ve tried both
map<string, ofstream> MyFileMap;
map<string, ofstream*> MyFileMap;
with both
.open
->open
neither of 4 variants work.
Solution (suggested in Rob’s code below):
Basically, I forgot “new”, the following works for me:
map<string, ofstream*> MyFileMap;
MyFileMap[*it] = new ofstream("/myhomefolder/"+(*it)+".");
std::map<std::string, std::ofstream>can’t possibly work, becausestd::maprequires its data type to be Assignable, whichstd::ofstreamisn’t. In the alternative, the data type must be a pointer to ofstream — either a raw pointer or a smart pointer.Here is how I would do it, using C++11 features:
and the 2nd verse, in C++03: