Przejdź do głównej zawartości

std::initializer_list constructors

Default constructor

initializer_list();
  • this constructor is constexpr and noexcept

Constructs an empty initializer list.

zanotuj

Despite a lack of constructors, it is possible to create non-empty initializer lists. Instances of std::initializer_list are implicitly constructed when:

  • a braced-init-list is used in list-initialization, including function-call list initialization and assignment expressions (not to be confused with constructor initializer lists)
  • a braced-init-list is bound to auto, including in a ranged for loop

Complexity

Constant - O(1).

Example

#include <initializer_list>
#include <iostream>
#include <vector>

int main() {
std::initializer_list<int> ilist; // default constructed

// implicitly construced initializer list
for(int i : { 1, 2, 3 }) std::cout << i << ' ';

// list initialization, implicitly constructed initializer list
std::vector<int> v = { 4, 5, 6, 7, 8 };
for(int i : v) std::cout << i << ' ';
}
Result
1 2 3 4 5 6 7 8
This article originates from this CppReference page. It was likely altered for improvements or editors' preference. Click "Edit this page" to see all changes made to this document.
Hover to see the original license.

std::initializer_list constructors

Default constructor

initializer_list();
  • this constructor is constexpr and noexcept

Constructs an empty initializer list.

zanotuj

Despite a lack of constructors, it is possible to create non-empty initializer lists. Instances of std::initializer_list are implicitly constructed when:

  • a braced-init-list is used in list-initialization, including function-call list initialization and assignment expressions (not to be confused with constructor initializer lists)
  • a braced-init-list is bound to auto, including in a ranged for loop

Complexity

Constant - O(1).

Example

#include <initializer_list>
#include <iostream>
#include <vector>

int main() {
std::initializer_list<int> ilist; // default constructed

// implicitly construced initializer list
for(int i : { 1, 2, 3 }) std::cout << i << ' ';

// list initialization, implicitly constructed initializer list
std::vector<int> v = { 4, 5, 6, 7, 8 };
for(int i : v) std::cout << i << ' ';
}
Result
1 2 3 4 5 6 7 8
This article originates from this CppReference page. It was likely altered for improvements or editors' preference. Click "Edit this page" to see all changes made to this document.
Hover to see the original license.