c++ - 如何设置一个以字符串为键、以 ostream 为值的映射?

标签 c++ dictionary stdmap ostream

我正在尝试使用 map C++ 中的容器,如下所示: key 是 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<string, int> foo; 测试我的代码它工作正常。

最佳答案

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

typedef map<string, ofstream*> mapType;

关于c++ - 如何设置一个以字符串为键、以 ostream 为值的映射?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1819603/

相关文章:

c++ - 为什么对象可能是 "moved"甚至缺少 move 构造函数和 move 赋值运算符?

c++ - 无法使用 std::string 作为键迭代 std::map

c++ - 如果键不存在,为什么 std::map operator[] 会创建一个对象?

Java数据结构,一个以value里面的对象为key的map

c++ - std::map 在初始化后更改 key_comp

c++ - 了解派生声明符类型列表和数组声明符

c++ - 在 Managed_shared_memory 中 boost 进程间互斥

c++ - 尝试将 Struct 指针传递给类时出错

c# - "An item with the same key has already been added"protobuf-net 错误

json - Alamofire 4、Swift 3 和构建 json 主体