c++ initialize_list
2024-09-06 00:55:24
看到这么一个东西,可以实现花括号( "{" "}" )初始化容器类。
使用时需包含头文件
#include <initialize_list>
我们都看过这样的代码
vector<int> arr = { ,,,, }; 或者 vector<int> arr{ ,,,, };
右边那个花括号返回的类型便是initialize_list
我们可以在自己的类中这么用
class foo {
public:
std::vector<int> data;
//构造函数里放上initialize_list
foo() {}
foo(std::initializer_list<int> list) :data(list) {} void print() {
for (auto item : data) {
std::cout << item;
}
std::cout << endl;
}
};
试验一下
int main() {
foo test1{ ,,,, };
foo test2 = { ,,,, };
test1.print();
test2.print();
return ;
}
可以正常输出
cppreference 的测试代码如下:可以看到这个东西的花样还是挺多的
#include <iostream>
#include <vector>
#include <initializer_list> template <class T>
struct S {
std::vector<T> v;
S(std::initializer_list<T> l) : v(l) {
std::cout << "constructed with a " << l.size() << "-element list\n";
}
void append(std::initializer_list<T> l) {
v.insert(v.end(), l.begin(), l.end());
}
std::pair<const T*, std::size_t> c_arr() const {
return{ &v[], v.size() }; // copy list-initialization in return statement
// this is NOT a use of std::initializer_list
}
}; template <typename T>
void templated_fn(T) {} int main()
{
S<int> s = { , , , , }; // copy list-initialization
s.append({ , , }); // list-initialization in function call std::cout << "The vector size is now " << s.c_arr().second << " ints:\n"; for (auto n : s.v)
std::cout << n << ' ';
std::cout << '\n'; std::cout << "Range-for over brace-init-list: \n"; for (int x : {-, -, -}) // the rule for auto makes this ranged-for work
std::cout << x << ' ';
std::cout << '\n'; auto al = { , , }; // special rule for auto std::cout << "The list bound to auto has size() = " << al.size() << '\n'; //templated_fn({1, 2, 3}); // compiler error! "{1, 2, 3}" is not an expression,
// it has no type, and so T cannot be deduced
templated_fn<std::initializer_list<int>>({ , , }); // OK
templated_fn<std::vector<int>>({ , , }); // also OK
}
最新文章
- 关于FloatingActionButton
- Java日志&mdash;&mdash;2016年5月30日
- 药企信息sop
- mybatis中oracle in>;1000的处理
- HYSBZ 1061 志愿者招募 【最小费用流】【差分】【最小费用流模板】
- 四则运算三+psp0级表格
- 三分钟学会缓存工具DiskLruCache
- Unity干中学——如何实现类似Windows Store 应用程序和Android Toast的通知?
- C语言基础学习运算符-赋值运算符
- A Simple Task
- Java采用内部构造器Builder模式进行对类进行构建
- SpringEl表达式(转)
- Aspnet mvc移除WebFormViewEngine
- 5.Django cookie
- LimeSDR 无线信号重放攻击和逆向分析
- Linker Scripts3--链接脚本概述
- WCF与WebService的区别(转)
- activiti学习第一天
- C++访问二维数组元素
- 21个ui设计技巧,让你的设计不落伍
热门文章
- oracle的minus返回第一个表中有、第二个表中没有的数据
- java俄罗斯方块游戏代码
- 【循序渐进学Python】7.面向对象的核心——类型(上)
- VS ";15"; 预览 5 中 VB 15 新增的功能
- 【转】RBAC权限管理
- 亲们! 首次见面! 带来不适!多多见谅!--------->;>;Bank系统
- JSON数据解析(转)
- SQL Server的各种表
- playframework中多附件上传注意事项
- .NET 面试题整理