正常
std::initializer_list (C++11)
In a Nutshell
A lightweight, read-only proxy object that allows us to conveniently pass an arbitrary number of homogeneous initial values to containers or custom classes using braces {}.
Header
#include <initializer_list>
Core API Quick Reference
| Operation | Signature | Description |
|---|---|---|
| Constructor | initializer_list() noexcept | Creates an empty list (usually implicitly constructed by the compiler) |
| Element Count | std::size_t size() const noexcept | Returns the number of elements in the list |
| Begin Pointer | const T* begin() const noexcept | Pointer to the first element |
| End Pointer | const T* end() const noexcept | Pointer to one past the last element |
| Begin Iterator | const T* begin(std::initializer_list<T> il) noexcept | Overload of std::begin |
| End Iterator | const T* end(std::initializer_list<T> il) noexcept | Overload of std::end |
Minimal Example
cpp
// Standard: C++11
#include <iostream>
#include <initializer_list>
#include <vector>
struct Container {
std::vector<int> v;
Container(std::initializer_list<int> l) : v(l) {}
void append(std::initializer_list<int> l) {
v.insert(v.end(), l.begin(), l.end());
}
};
int main() {
Container c = {1, 2, 3}; // 隐式构造 initializer_list
c.append({4, 5});
for (int x : c.v) std::cout << x << ' ';
}Embedded Applicability: High
- The underlying implementation typically contains only a pointer and a size (or two pointers), resulting in minimal memory overhead.
- Copying a
std::initializer_listdoes not copy the underlying array; it only copies the proxy object itself, incurring no additional allocation overhead. - The underlying array may reside in read-only memory, making it suitable for initializing static configuration tables stored in ROM.
Compiler Support
| GCC | Clang | MSVC |
|---|---|---|
| To be added | To be added | To be added |
See Also
Part of the content references cppreference.com, licensed under CC-BY-SA 4.0