كيف يمكنني إعداد خريطة مع سلسلة كمفتاح وostream كقيمة؟

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

سؤال

وأنا أحاول أن استخدام الحاويات map في C ++ بالطريقة التالية: مفتاح هو 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; أنه يعمل بشكل جيد

هل كانت مفيدة؟

المحلول

وتيارات لا أحب يتم نسخها. أبسط حل يستخدم مؤشر (أو أفضل، مؤشر الذكية) إلى دفق في الخريطة:

typedef map<string, ofstream*> mapType;

نصائح أخرى

وكائنات من نوع ofstream لا copiable، وهو شرط مسبق لوضعها في أي حاوية مكتبة قياسي.

ووoperator= هو خاص لstd::ios_base، الذي يشتق ofstream. لذلك لا يمكن نسخ foo1 الأشياء وfoo2.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top