看到这么一个东西,可以实现花括号( "{" "}" )初始化容器类。

使用时需包含头文件

#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
}

最新文章

  1. 关于FloatingActionButton
  2. Java日志&mdash;&mdash;2016年5月30日
  3. 药企信息sop
  4. mybatis中oracle in&gt;1000的处理
  5. HYSBZ 1061 志愿者招募 【最小费用流】【差分】【最小费用流模板】
  6. 四则运算三+psp0级表格
  7. 三分钟学会缓存工具DiskLruCache
  8. Unity干中学——如何实现类似Windows Store 应用程序和Android Toast的通知?
  9. C语言基础学习运算符-赋值运算符
  10. A Simple Task
  11. Java采用内部构造器Builder模式进行对类进行构建
  12. SpringEl表达式(转)
  13. Aspnet mvc移除WebFormViewEngine
  14. 5.Django cookie
  15. LimeSDR 无线信号重放攻击和逆向分析
  16. Linker Scripts3--链接脚本概述
  17. WCF与WebService的区别(转)
  18. activiti学习第一天
  19. C++访问二维数组元素
  20. 21个ui设计技巧,让你的设计不落伍

热门文章

  1. oracle的minus返回第一个表中有、第二个表中没有的数据
  2. java俄罗斯方块游戏代码
  3. 【循序渐进学Python】7.面向对象的核心——类型(上)
  4. VS &quot;15&quot; 预览 5 中 VB 15 新增的功能
  5. 【转】RBAC权限管理
  6. 亲们! 首次见面! 带来不适!多多见谅!---------&gt;&gt;Bank系统
  7. JSON数据解析(转)
  8. SQL Server的各种表
  9. playframework中多附件上传注意事项
  10. .NET 面试题整理