可以更改initializer_list容器吗?

时间:2016-07-07 13:10:30

标签: visual-c++ initializer-list stdmap

似乎容器元素在初始化后是不可更改的。在示例代码中,我想将A的ch更改为'c',但是我收到错误:

#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)为什么编译器要求默认构造函数?

1 个答案:

答案 0 :(得分:0)

仔细检查initializer_list的_Elem类型,我看到有一个非常量的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;
}