请先考虑下面的例子:
为什么我们不能在示例中使用std::initializer_list的对象来初始化数组?
我遇到了这个错误:
#include <iostream>
#include <initializer_list>
#include <vector>
#include <array>
#include <set>
int main(){
std::initializer_list il1={1,2,3,4,5};
std::initializer_list il2{1,2,3,4,5};
std::vector<int> v1 = il1; //this work - by means of COPY
std::set<int> s1 = il1; //this work - by means of COPY
std::array<int, 5> a1 = {1,2,3,4,5}; //this work
std::array<int, 5> a2 = il1; //this didn't work? - not compatable ?
int array1[5] = {1,2,3,4,5}; //this work
int array2[5] = il2; //this didn't work? - not compatable ?
}
为什么我们不能在示例中使用std::initializer_list的对象来初始化数组?
我遇到了这个错误:
<source>: In function 'int main()':
<source>:15:29: error: conversion from 'std::initializer_list<int>' to non-scalar type 'std::array<int, 5>' requested
15 | std::array<int, 5> a2 = il1; //this didn't work? - not compatable ?
| ^~~
<source>:17:21: error: array must be initialized with a brace-enclosed initializer
17 | int array2[5] = il2; //this didn't work? - not compatable ?
|
而且在 il1 (在 std::initializer_list il1={1,2,3,4,5};) 和单独的 {1,2,3,4,5} 之间是否有任何特定差异?
std::array
都是聚合体,而聚合体只能使用聚合初始化进行初始化。不可能使用其他无关的对象进行聚合初始化。普通数组甚至不能进行复制初始化(所以例如int array3[5] = array1;
是不可能的)。然而,std::array
允许使用相同类型的另一个std::array
对象进行复制语义。 - Some programmer dudeset
和vector
之间有什么区别?一旦你理解了为什么对于set
和vector
有效,你就会明白为什么对于array
无效。 - 463035818_is_not_an_ai