c++ - 以下基于范围的 for 循环内幕后的列表是什么?

标签 c++ for-loop

我正在学习 C++,我看到了一个基于范围的 for 循环,如下所示:

for (int i : {1,2,3,4,5})
    std::cout << i << ' ';

幕后for循环中的临时{1,2,3,4,5}是什么?

最佳答案

这里的对象是 std::initializer_list<int> 的一个实例.来自引用(强调我的):

A std::initializer_list object is automatically constructed when:

a braced-init-list is used to list-initialize an object, where the corresponding constructor accepts an std::initializer_list parameter

a braced-init-list is used as the right operand of assignment or as a function call argument, and the corresponding assignment operator/function accepts an std::initializer_list parameter

a braced-init-list is bound to auto, including in a ranged for loop

关于c++ - 以下基于范围的 for 循环内幕后的列表是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54070743/

相关文章:

c++ - 将 int 附加到 wchar_t*? ..未解决,缺乏具体的例子

c++ - 如何在 C++ 中包含、加载和使用 .dll

java - 使用单个 for Loop 或使用 Any Collection 检查数组中所有数字的出现次数

java - 当从 ArrayList 中删除多个项目时,为什么最好使用 while 循环而不是递减 for 循环?

c++ - 我们能够在 C++20 中构造带有 View 的容器吗?

c++ - 如何将 int 和 int* 传递给函数来定义变量

c++ - tbb::concurrent_hash_map - 如果键输入被其他线程阻塞,如何返回

r for 循环在单个数据框中导入 xlsx 文件

javascript - 单击时如何在导航栏元素下划线?

javascript - 我需要在单击输入框时显示我的段落。我的 p 数组如何不循环遍历我的段落变量?