Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set up a map with string as key and ostream as value?

I am trying to use the map container in C++ in the following way: The Key is a string and the value is an object of type ofstream. My code looks as follows:

#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;
}

However, when I try to compile the above code, I get the following 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

What is going wrong? If this cannot be done using map, is there some other way to create such key:value pair?

Note: If I test my code with map<string, int> foo; it works fine.

like image 317
apt Avatar asked Nov 30 '09 12:11

apt


People also ask

How do you add a string value to a string map?

Maps are associative containers that store elements in a specific order. It stores elements in a combination of key values and mapped values. To insert the data in the map insert() function in the map is used.

Can I store string in map?

*You can Create map of both String and Integer, just keep sure that your key is Unique. I hope you find the above solution helpful.

Can we use string in map in C++?

A map is an associative container that maps keys to values, provides logarithmic complexity for inserting and finding, and constant time for erasing single elements. It is common for developers to use a map to keep track of objects by using a string key.


1 Answers

Streams do 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;
like image 115
gnud Avatar answered Sep 29 '22 20:09

gnud