2016-07-07 26 views
0

コンテナ要素は、初期化後も変更できないようです。サンプルコードでは、私は、「C」にAのCHを変更したいが、私はエラーを取得:initializer_listコンテナを変更できますか?

#include "stdafx.h" 
#include <memory> 
#include <map> 

struct A 
{ 
    A(char ch) {} 
}; 

struct H 
{ 
    H(std::initializer_list< std::pair< const int, A > > initializerList) : myMap(initializerList) {} 

    std::map< const int, A > myMap; 
}; 

int main() 
{ 
    H h { { 33, 'a' }, { 44, 'b' } }; 

    //h.myMap[ 33 ] = 'c'; // error C2512: 'A::A': no appropriate default constructor available 

    return 0; 
} 

エラーテキストの残りの部分はこれです:

c:\program files (x86)\microsoft visual studio 14.0\vc\include\tuple(1203): note: see reference to function template instantiation 'std::pair<const int,A>::pair<std::tuple<_Ty &&>,std::tuple<>,0,>(_Tuple1 &,_Tuple2 &,std::integer_sequence<size_t,0>,std::integer_sequence<size_t>)' being compiled 
with 
[ 
    _Ty=const int, 
    _Tuple1=std::tuple<const int &&>, 
    _Tuple2=std::tuple<> 
] 

私の質問は次のとおりです。1 )初期化子リストのコンテナデータ、この場合はstd :: mapを変更可能にすることはできますか? 2)コンパイラがデフォルトのコンストラクタを要求するのはなぜですか?

答えて

0

initializer_listの_Elemタイプを詳しく調べると、非constイテレータがあることがわかります。

#include "stdafx.h" 
#include <memory> 
#include <map> 

struct A 
{ 
    A(char ch) : ch(ch) {} 
    char ch; 
}; 

struct H 
{ 
    H(std::initializer_list< std::pair< const int, std::shared_ptr<A> > > initializerList) : myMap(initializerList) {} 

    std::map< const int, std::shared_ptr<A> > myMap; 
}; 

int main() 
{ 
    H h { { 33, std::make_shared<A>('a') }, { 44, std::make_shared<A>('b') } }; 

    h.myMap[ 33 ] = std::make_shared<A>('c'); // ok 

    return 0; 
} 

#include "stdafx.h" 
#include <memory> 
#include <map> 

struct A 
{ 
    A(char ch) : ch(ch) {} 
    char ch; 
}; 

struct H 
{ 
    H(std::initializer_list< std::pair< const int, A* > > initializerList) : myMap(initializerList) {} 

    std::map< const int, A* > myMap; 
}; 

int main() 
{ 
    H h { { 33, new A('a') }, { 44, new A('b') } }; 

    h.myMap[ 33 ] = new A('c'); // ok 

    return 0; 
} 

このコードのスマートポインタのバージョンはこれです:私は今、働く元のコードを変更しました

関連する問題