【问题标题】:How can I set up a map with string as key and ostream as value?如何设置以字符串为键、以 ostream 为值的映射?
【发布时间】:2009-11-30 12:41:22
【问题描述】:

我正在尝试通过以下方式在 C++ 中使用map 容器:键是string,值是ofstream 类型的对象。我的代码如下所示:

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

但是,当我尝试编译上述代码时,出现以下错误:

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

出了什么问题?如果使用map 无法做到这一点,是否有其他方法可以创建这样的键:值对?

注意:如果我使用 map&lt;string, int&gt; foo; 测试我的代码,它可以正常工作。

【问题讨论】:

  • 作为一种风格,您可以将 fooMap 定义为 mapType 例如地图类型 fooMap;因为你已经定义了它。

标签: c++ dictionary stdmap ostream


【解决方案1】:

流不喜欢被复制。最简单的解决方案是使用指向地图中流的指针(或者更好的是智能指针):

typedef map<string, ofstream*> mapType;

【讨论】:

  • 智能指针在这里没有任何意义,除非您也将分配更改为使用new
  • 如果您确实使用智能指针,请避免使用 auto_ptr。在这种情况下,您不希望转让所有权。
【解决方案2】:

ofstream 类型的对象不可复制,这是放入任何标准库容器的先决条件。

【讨论】:

    【解决方案3】:

    operator=std::ios_base 是私有的,ofstream 是从其派生的。所以你不能复制对象foo1foo2

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-10
      • 2018-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多