キーとして文字列、値としてostreamを使用してマップを設定するにはどうすればよいですか?

StackOverflow https://stackoverflow.com/questions/1819603

質問

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をコピーすることはできません。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top