キーとして文字列、値としてostreamを使用してマップを設定するにはどうすればよいですか?
-
10-07-2019 - |
質問
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<string, int> foo;
を使用してこれを実行できない場合、そのようなkey:valueペアを作成する他の方法はありますか?
注:<=>でコードをテストすると、正常に動作します。
解決
ストリームはコピーされることを好みません。最も簡単な解決策は、マップ内のストリームへのポインター(または、より優れた、スマートポインター)を使用することです。
typedef map<string, ofstream*> mapType;
他のヒント
タイプofstream
のオブジェクトはコピーできません。これは、標準ライブラリコンテナに配置するための前提条件です。
operator=
はstd::ios_base
のプライベートであり、ofstream
の派生元です。したがって、オブジェクトfoo1
およびfoo2
をコピーすることはできません。
所属していません StackOverflow