對于array
的初始化我們可以使用列表初始化:
array<int, 8> test = {1,2,3,4,5,6,7,8
};
但是當我們不再使用簡單的內置類型array
時:
array<pair<int, int>, 8> dirs = {{-1, -1},{-1, 0},{-1, 1},{0, -1},{0, 1},{1, -1},{1, 0},{1, 1},
};
編譯器就會報錯:No viable conversion from 'int' to 'std::pair<int, int>'
但是如果使用雙層大括號,就像這樣:
array<pair<int, int>, 8> dirs = {{{-1, -1},{-1, 0},{-1, 1},{0, -1},{0, 1},{1, -1},{1, 0},{1, 1},
}};
編譯器就不會報錯,是不是很神奇。
經過在網上查閱資料,看到stackoverflow
上一個人解釋說,array
的原型是結構體中的數組:
template<typename T, int size>
struct std::array
{T a[size];
};
因此,產生了需要雙大括號的問題:最外面的大括號是給結構體初始化用的,里面的大括號是給數組初始化用的。
但是標準中并沒有提到這一點,因此這個可能是編譯器的bug