tags:

views:

210

answers:

3
+1  Q: 

using <map> in C++

hi,

I am trying to use "map" container in C++ in the following way:

  • Key is a string and mapping value is an object of type ofstream. If I execute the following code, I get an error that is copied at the end of the message. Could someone please let me know what is going wrong? If it can not be done using 'map' is there some other way to create such key:value pair? I would appreciate your response.

Note: If I test the following code with map foo; it works fine.

Code:

#include <string>
#include <iostream>
#include <map>
#include <fstream>

using namespace std;

int main()
{



  // typedef map<string, int> mapType2;
  // map<string, int> foo;

  typedef map<string, ofstream> mapType;
  map<string, ofstream> fooMap;

  ofstream foo1;
  ofstream foo2; 


  fooMap["file1"] = foo1;
  fooMap["file2"]= foo2;

  mapType::iterator iter = fooMap.begin();
  cout<< "Key = " <<iter->first;

}

Error:

C:/Dev-Cpp/bin/../lib/gcc/mingw32/3.4.2/../../../../include/c++/3.4.2/bits/ios_base.h:
In member function `std::basic_ios<char, std::char_traits<char> >& std::basic_ios<char, std::char_traits<char> >::operator=(const std::basic_ios<char, std::char_traits<char> >&)': 
C:/Dev-Cpp/bin/../lib/gcc/mingw32/3.4.2/../../../../include/c++/3.4.2/bits/ios_base.h:741:
error: `std::ios_base& std::ios_base::operator=(const std::ios_base&)' is private
hash.cpp:88: error: within this context
+1  A: 

ofstream aren't copiable, which is a precondition to be put in any SL container.

AProgrammer
+9  A: 

Streams does not like being copied. The simplest solution is using a pointer (or better, a smart pointer) to a stream in the map.

typedef map<string, ofstream*> mapType;
gnud
Smart pointer doesn't really mean anything here, unless you also change the allocation to use `new`.
jleedev
If you do use a smart pointer, avoid auto_ptr. You don't want transfer of ownership on assignment in this case.
christopher_f
+1  A: 

operator= is private for std::ios_base, from which ofstream is derived. So you can't copy the objects foo1 and foo2.

Vijay Mathew