如何设置一个以字符串为键,ostream为值的地图?
-
10-07-2019 - |
题
我试图通过以下方式在C ++中使用map
容器: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<string, int> foo;
无法做到这一点,是否还有其他方法可以创建这样的键:值对?
注意:如果我用<=>测试我的代码,它可以正常工作。
解决方案
Streams不喜欢被复制。最简单的解决方案是使用指针(或更好的智能指针)到地图中的流:
typedef map<string, ofstream*> mapType;
其他提示
ofstream
类型的对象不可复制,这是放入任何标准库容器的前提条件。
operator=
是std::ios_base
的私有,ofstream
从中派生。因此,您无法复制对象foo1
和foo2
。
不隶属于 StackOverflow