如何设置以 string 作为键、ostream 作为值的映射?
我尝试按以下方式在 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
它工作正常。
I am trying to use the map
container in C++ in the following way: The Key is a string
and the value is an object of type ofstream
. My code looks as follows:
#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;
}
However, when I try to compile the above code, I get the following error:
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
What is going wrong? If this cannot be done using map
, is there some other way to create such key:value pair?
Note: If I test my code with map<string, int> foo;
it works fine.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
流不喜欢被复制。最简单的解决方案是使用指向映射中流的指针(或者更好的是智能指针):
Streams do not like being copied. The simplest solution is using a pointer (or better, a smart pointer) to a stream in the map:
ofstream
类型的对象不可复制,这是放入任何标准库容器的先决条件。Objects of type
ofstream
aren't copiable, which is a precondition to be put into any Standard Library container.operator=
是std::ios_base
私有的,ofstream
是从中派生的。因此您无法复制对象foo1
和foo2
。The
operator=
is private forstd::ios_base
, from whichofstream
is derived. So you can't copy the objectsfoo1
andfoo2
.