6

The following code compiles with gcc-4.5.1 but not in Visual Studio 11.

#include <map>
#include <array>

typedef std::pair<const unsigned int, std::array<const unsigned int, 4>> pairus;

int main(){

   std::map<const unsigned int, std::array<const unsigned int, 4> > x; 
   std::array<const unsigned int, 4> troll = {1, 2, 3, 4};
   x.insert(pairus(1, troll));

   auto z = x[1];
}

1 is now mapped to std::array<> troll. The insertion works well and the program compiles. But, as soon as i try auto z = x[1] -> Therefore trying to get the array troll that 1 is mapped to, the program does not compile with the following error:

error C2512: 'std::array<_Ty,_Size>::array' : no appropriate default constructor available

What causes this difference in behavior between gcc and vs11 and how to fix it ?

Thanks.

4

2 に答える 2

4

auto z = *x.find(1);代わりに試してください。-operator[]には、デフォルトで構築可能な型が必要です。実際、コンテナ全体がデフォルトで構築可能な型を必要とするため、さまざまな実装を試してみると、たまたまの運以外は何も期待できません。

于 2012-05-06T00:36:53.847 に答える
3

定数が含まれているため、型を割り当てることができません。

x[1] は、割り当て可能な参照を返そうとします。キーがまだ存在しない場合は、キーの空の値も作成します。これらはどちらもあなたのタイプでは無効です。代わりに find を使用する必要があります。

于 2012-05-06T00:39:10.620 に答える