在C++中使用<map>

apt*_*apt 5 c++ dictionary stdmap ostream

我试图通过以下方式在C++中使用"map"容器:

  • Key是字符串,映射值是ofstream类型的对象.如果我执行以下代码,则会收到在消息末尾复制的错误.有人可以让我知道出了什么问题吗?如果使用'map'无法完成,还有其他方法可以创建这样的键:值对吗?非常感谢您的回复.

注意:如果我使用map foo测试以下代码; 它工作正常.

码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

错误:

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
Run Code Online (Sandbox Code Playgroud)

gnu*_*nud 12

Streams不喜欢被复制.最简单的解决方案是使用指针(或更好的智能指针)来映射地图中的流.

typedef map<string, ofstream*> mapType;
Run Code Online (Sandbox Code Playgroud)