2016-07-07 66 views
0

看起來容器元素在初始化後是不可更改的。在示例代碼,我想換一個的通道,以「C」,但我得到一個錯誤:可以更改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 interator。我已經改變了原來的代碼現在工作:

#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; 
} 

這段代碼的智能指針的版本是這樣的:

#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; 
} 
相關問題