c++ 疑难杂症(10) std::initializer_list
liebian365 2024-11-18 14:21 22 浏览 0 评论
std::initializer_list 是 C++11 引入的一个新特性,主要用于支持统一初始化语法(也称为大括号初始化)。引入 std::initializer_list 的原因主要有以下几点:
- 初始化方式的统一:在 C++11 之前,初始化对象的方式有很多种,包括等号初始化、括号初始化、构造函数初始化等。这种多样性可能会导致混乱和错误。引入 std::initializer_list 和大括号初始化语法后,C++ 提供了一种更统一、更简洁的初始化方式。
- 支持任意数量的初始化参数:std::initializer_list 可以接受任意数量的同类型参数,这使得它非常适合用于初始化数组、向量等容器。在之前的 C++ 版本中,要实现这种功能通常需要借助变长参数模板或其他复杂技术。
- 类型安全:std::initializer_list 是类型安全的,这意味着它只接受指定类型的元素。这有助于在编译时捕获类型错误,从而提高代码的安全性。
- 性能优化:由于 std::initializer_list 在编译时确定其元素数量和类型,因此编译器可以进行一些优化,例如将列表中的元素直接存储在静态存储区中,从而提高性能。
- 与现有代码的兼容性:引入 std::initializer_list 和大括号初始化语法后,C++ 仍然保留了之前的初始化方式,以确保与现有代码的兼容性。这意味着开发者可以根据需要选择使用新的初始化方式或继续使用旧的方式。
1. std::initializer_list
std::initializer_list<T> 类型对象是一个访问 const T 类型对象数组的轻量代理对象。
std::initializer_list 对象在这些时候自动构造:
- 用花括号初始化列表?? 列表初始化一个对象,其中对应构造函数接受一个 std::initializer_list 参数
- 以花括号初始化列表?? 为赋值的右运算数,或函数调用参数,而对应的赋值运算符/函数接受 std::initializer_list 参数
- 绑定花括号初始化列表?? 到 auto,包括在范围 for 循环中
std::initializer_list 可由一对指针或指针与其长度实现。复制一个 std::initializer_list 不会复制它对应的初始化列表的基底数组。
如果声明了 std::initializer_list 的显式(全)或偏特化,那么程序非良构。
实现比较简单, 直接把源码贴出来.
namespace std
{
/// initializer_list
template<class _E>
class initializer_list
{
public:
typedef _E value_type;
typedef const _E& reference;
typedef const _E& const_reference;
typedef size_t size_type;
typedef const _E* iterator;
typedef const _E* const_iterator;
private:
iterator _M_array;
size_type _M_len;
// The compiler can call a private constructor.
constexpr initializer_list(const_iterator __a, size_type __l)
: _M_array(__a), _M_len(__l) { }
//这里很关键, 供编译器调用, 实际使用
public:
constexpr initializer_list() noexcept
: _M_array(0), _M_len(0) { }
//创建空的初始化器列表
// Number of elements.
constexpr size_type
size() const noexcept { return _M_len; }
//返回初始化器列表中的元素数目
// First element.
constexpr const_iterator
begin() const noexcept { return _M_array; }
//返回指向首元素的指针
// One past the last element.
constexpr const_iterator
end() const noexcept { return begin() + size(); }
//返回指向末元素后一位置的指针
};
/**
* @brief Return an iterator pointing to the first element of
* the initilizer_list.
* @param __ils Initializer list.
*/
template<class _Tp>
constexpr const _Tp*
begin(initializer_list<_Tp> __ils) noexcept
{ return __ils.begin(); }
//特化 std::begin()
/**
* @brief Return an iterator pointing to one past the last element
* of the initilizer_list.
* @param __ils Initializer list.
*/
template<class _Tp>
constexpr const _Tp*
end(initializer_list<_Tp> __ils) noexcept
{ return __ils.end(); }
//特化 std::end()
}
2. 示例
- 用花括号初始化列表?? 列表初始化一个对象,其中对应构造函数接受一个 std::initializer_list 参数
#include <string>
#include <list>
#include <vector>
#include <map>
int main() {
std::list<int> lst({ 1, 2, 3, 4, 5, 6 });
std::vector<double> vec = { 0.1, 0.2, 0.3 };
std::map<int, std::string> map({ { 1, "1" }, {2, "2"} });
std::map<int, std::string> map2{ { 1, "1" }, {2, "2"} };
return 0;
}
- 以花括号初始化列表?? 为赋值的右运算数,或函数调用参数,而对应的赋值运算符/函数接受 std::initializer_list 参数
#include <iostream>
#include <string>
#include <map>
#include <list>
#include <vector>
void func(std::initializer_list<int>& il) {
std::cout << "func : ";
for (auto x : il) {
std::cout << x << " ";
}
std::cout << std::endl;
}
int main() {
std::list<int> lst;
std::vector<double> vec;
std::map<int, std::string> map;
//operator=
lst = { 1, 2, 3, 4, 5, 6 };
vec = { {0.1, 0.2, 0.3} };
map = { {1, "3"}, {2, "6"} };
//函数(insert(const_iterator _Where, initializer_list<_Ty> _Ilist))
lst.insert(lst.end(), { 9, 10 });
//函数/lambda调用
std::initializer_list<int> xx{ 1, 2, 3, 4, 5 };
//auto xx = { 1, 2, 3, 4, 5 }; //ok, 可自动推导
func(xx);
auto show = [](std::initializer_list<int>& il) {
std::cout << "lambda : ";
for (auto x : il) {
std::cout << x << " ";
}
std::cout << std::endl;
};
show(xx);
return 0;
}
/*打印输出:
func : 1 2 3 4 5
lambda : 1 2 3 4 5
*/
- 绑定花括号初始化列表?? 到 auto,包括在范围 for 循环中
#include <iostream>
#include <initializer_list>
int main() {
//构建了 std::initializer_list<int>
for (int x : {3, 6, 1, 2}) {
//for (int& x : { 3, 6, 1, 2 }) { //错误, 常量不能改变
//for (const int& x : {3, 6, 1, 2}) { //ok
std::cout << x << " ";
}
std::cout << std::endl;
//推导为 std::initializer_list<double>
auto al = {0.1, .2, 0.3, .5};
std::cout<<"size="<<al.size()<<std::endl;
for (const double& x : al) {
//for (const auto& x : al) { //ok
std::cout << x << " ";
}
std::cout << std::endl;
//注意是 const double*
for (const double* iter = al.begin(); iter != al.end(); ++iter) {
//for (auto iter = al.begin(); iter != al.end(); ++iter) {
std::cout << *iter << " ";
}
std::cout << std::endl;
return 0;
}
/*打印输出:
3 6 1 2
size=4
0.1 0.2 0.3 0.5
0.1 0.2 0.3 0.5
*/
- 自定义
#include <iostream>
#include <string>
#include <initializer_list>
int main() {
class A {
public:
A(std::initializer_list<int> il) {
std::cout << "int : ";
for (const auto& x : il) {
std::cout << x << " ";
}
std::cout << std::endl;
}
A(std::initializer_list<double> il) {
std::cout << "double : ";
for (const auto& x : il) {
std::cout << x << " ";
}
std::cout << std::endl;
}
A(std::initializer_list<std::string> il) {
std::cout << "string : ";
for (const auto& x : il) {
std::cout << x << " ";
}
std::cout << std::endl;
}
void DoSomething(std::initializer_list<int> il) {
std::cout << "DoSomething : ";
for (const auto& x : il) {
std::cout << x << " ";
}
std::cout << std::endl;
}
};
A a1{1, 2, 3, 4};
A a2{ 0.1, .2, .3, .4 };
A a3{ "a", "b", "c", "d"};
a3.DoSomething({9, 99, 999});
return 0;
}
/*打印输出:
int : 1 2 3 4
double : 0.1 0.2 0.3 0.4
string : a b c d
DoSomething : 9 99 999
*/
相关推荐
- 4万多吨豪华游轮遇险 竟是因为这个原因……
-
(观察者网讯)4.7万吨豪华游轮搁浅,竟是因为油量太低?据观察者网此前报道,挪威游轮“维京天空”号上周六(23日)在挪威近海发生引擎故障搁浅。船上载有1300多人,其中28人受伤住院。经过数天的调...
- “菜鸟黑客”必用兵器之“渗透测试篇二”
-
"菜鸟黑客"必用兵器之"渗透测试篇二"上篇文章主要针对伙伴们对"渗透测试"应该如何学习?"渗透测试"的基本流程?本篇文章继续上次的分享,接着介绍一下黑客们常用的渗透测试工具有哪些?以及用实验环境让大家...
- 科幻春晚丨《震动羽翼说“Hello”》两万年星间飞行,探测器对地球的最终告白
-
作者|藤井太洋译者|祝力新【编者按】2021年科幻春晚的最后一篇小说,来自大家喜爱的日本科幻作家藤井太洋。小说将视角放在一颗太空探测器上,延续了他一贯的浪漫风格。...
- 麦子陪你做作业(二):KEGG通路数据库的正确打开姿势
-
作者:麦子KEGG是通路数据库中最庞大的,涵盖基因组网络信息,主要注释基因的功能和调控关系。当我们选到了合适的候选分子,单变量研究也已做完,接着研究机制的时便可使用到它。你需要了解你的分子目前已有哪些...
- 知存科技王绍迪:突破存储墙瓶颈,详解存算一体架构优势
-
智东西(公众号:zhidxcom)编辑|韦世玮智东西6月5日消息,近日,在落幕不久的GTIC2021嵌入式AI创新峰会上,知存科技CEO王绍迪博士以《存算一体AI芯片:AIoT设备的算力新选择》...
- 每日新闻播报(September 14)_每日新闻播报英文
-
AnOscarstatuestandscoveredwithplasticduringpreparationsleadinguptothe87thAcademyAward...
- 香港新巴城巴开放实时到站数据 供科技界研发使用
-
中新网3月22日电据香港《明报》报道,香港特区政府致力推动智慧城市,鼓励公私营机构开放数据,以便科技界研发使用。香港运输署21日与新巴及城巴(两巴)公司签署谅解备忘录,两巴将于2019年第3季度,开...
- 5款不容错过的APP: Red Bull Alert,Flipagram,WifiMapper
-
本周有不少非常出色的app推出,鸵鸟电台做了一个小合集。亮相本周榜单的有WifiMapper's安卓版的app,其中包含了RedBull的一款新型闹钟,还有一款可爱的怪物主题益智游戏。一起来看看我...
- Qt动画效果展示_qt显示图片
-
今天在这篇博文中,主要实践Qt动画,做一个实例来讲解Qt动画使用,其界面如下图所示(由于没有录制为gif动画图片,所以请各位下载查看效果):该程序使用应用程序单窗口,主窗口继承于QMainWindow...
- 如何从0到1设计实现一门自己的脚本语言
-
作者:dong...
- 三年级语文上册 仿写句子 需要的直接下载打印吧
-
描写秋天的好句好段1.秋天来了,山野变成了美丽的图画。苹果露出红红的脸庞,梨树挂起金黄的灯笼,高粱举起了燃烧的火把。大雁在天空一会儿写“人”字,一会儿写“一”字。2.花园里,菊花争奇斗艳,红的似火,粉...
- C++|那些一看就很简洁、优雅、经典的小代码段
-
目录0等概率随机洗牌:1大小写转换2字符串复制...
- 二年级上册语文必考句子仿写,家长打印,孩子照着练
-
二年级上册语文必考句子仿写,家长打印,孩子照着练。具体如下:...
你 发表评论:
欢迎- 一周热门
- 最近发表
- 标签列表
-
- wireshark怎么抓包 (75)
- qt sleep (64)
- cs1.6指令代码大全 (55)
- factory-method (60)
- sqlite3_bind_blob (52)
- hibernate update (63)
- c++ base64 (70)
- nc 命令 (52)
- wm_close (51)
- epollin (51)
- sqlca.sqlcode (57)
- lua ipairs (60)
- tv_usec (64)
- 命令行进入文件夹 (53)
- postgresql array (57)
- statfs函数 (57)
- .project文件 (54)
- lua require (56)
- for_each (67)
- c#工厂模式 (57)
- wxsqlite3 (66)
- dmesg -c (58)
- fopen参数 (53)
- tar -zxvf -c (55)
- 速递查询 (52)