我正在尝试使用 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/