当前位置:网站首页>initializer_ List tool library learning
initializer_ List tool library learning
2022-07-25 23:32:00 【I washed my feet in Bangong Lake】
initializer_list Is the initialization list class , And vector,list,map Such as compared to , Using it directly is less , But it is used in the initialization of many classes or templates , Because it is an initialization list , So it means , Yes initializer_list Can't add , Delete , Change , It's equivalent to const Datalist , Therefore, it provides relatively few functions , Only size(), begin(), end(), Nonmember functions std::begin(std::initializer_list),std::end(std::initializer_list),
stay c++11 Before , If we want to be right vector To initialize 5 Elements , We need this
vector<int> vec;
vec.push_back(1);
vec.push_back(2);
vec.push_back(3);
vec.push_back(4);
vec.push_back(5);
C++11 in the future , I can directly use the following code
vector<int> vec = {1,2,3,4,5};
Why can it be like this , original vector Constructor reference of , There is one initializer_list<T> Parameters of , Here is VS2017 vector The source code in the header file

It's not just vector, list, map, set, forward_list Constructors such as support list initialization
Here is list Constructor functions initializer_list Parameters

Here is map Constructor functions initializer_list Parameters
Here is an example of its use :
#include <iostream>
#include <string>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <forward_list>
#include <initializer_list>
using namespace std;
int main()
{
vector<int> vec = {1,2,3,4,5};
cout << "vector ================== ";
for(auto v: vec)
{
cout << v << "\t";
}
cout << endl;
list<int> lis = {1,2,3,4,5};
cout << "list ==================== ";
for(auto l: lis)
{
cout << l << "\t";
}
cout << endl;
map<int, string> ma = {
{1, "first"}, {2, "second"}, {3, "three"}};
cout << "map ===================== ";
for(auto m: ma)
{
cout << m.first << "==>" << m.second << "\t";
}
cout << endl;
initializer_list<int> init_list = {1,2,3,4,5,6,7,8,9};
cout << "initializer_list ======== ";
for(auto init_: init_list)
{
cout << init_ << "\t";
}
cout << endl;
//size return initializer_list The total number of elements
cout << "init_list.size=========== " << init_list.size() << endl;
//begin Point to initializer_list First element
cout << "init_list.first========== " << *init_list.begin() << endl;
//end Point to initializer_list The next position of the last element
initializer_list<int>::iterator end1 = init_list.end();
end1--;
cout << "init_list.last=========== " << *end1 << endl;
//std::begin Point to initializer_list First element
cout << "std::begin(init_list)==== " << *std::begin(init_list) << endl;
//std::end Point to initializer_list The next position of the last element
initializer_list<int>::iterator stdEnd = std::end(init_list);
--stdEnd;
cout << "std::end(init_list)====== " << *stdEnd << endl;
//*stdEnd = 50; // Constant iterator returned , You can't change its value
cout << "Hello World!" << endl;
return 0;
}
Running results :

initializer_list Use in functions and classes :
#include <iostream>
#include <vector>
#include <initializer_list>
using namespace std;
template<class T>
struct InitList{
std::vector<T> vec;
InitList()// Default constructor
{
cout << "default constructor==============" << endl;
vec.clear();
}
InitList(T param1, T param2)// Constructor with parameters
{
cout << "parametric constructor ==============" << endl;
vec.push_back(param1);
vec.push_back(param2);
}
InitList(initializer_list<T> li)// Initialize the list constructor
:vec(li)
{
cout << "constructed with a " << li.size() << " -element list \n";
}
void append(initializer_list<T> li) // Function with list argument
{
vec.insert(vec.end(), li.begin(), li.end());
}
std::pair<const T*, std::size_t> c_arr() const {
return {&vec[0], vec.size()};// stay return Statement, copy list initialization , It doesn't use std::initializer_list
}
};
template <typename T>
void templated_fn(T) { cout << "call templated_fn ======== " << endl; }
int main()
{
InitList<int> init1;
InitList<int> init2(20, 31);
InitList<int> init3 = {23,34,56,76,98};
init3.append({82, 15, 39});
cout << "the vector size is now " << init3.c_arr().second << " ints:\n";
for(auto n: init3.vec)
cout << n << " ";
cout << endl;
cout << "Range-for over brace-init-list:\n";
for(int x: {-10, -15, -18}) //auto The rules of the law make this band for Work
cout << x << " ";
cout << endl;
auto alint = {13, 15, 18};//auto The special rules of
cout << "the list bound to auto has size() = " << alint.size() << endl;
//templated_fn({11,22,33}); // Compile error {11,22,33} It's not an expression , It has no type , so T It's impossible to deduce
templated_fn<initializer_list<int>>({11,22,33}); //OK
templated_fn<vector<int>>({11,22,33}); // also OK
cout << "Hello World!" << endl;
return 0;
}
Running results :

Reference resources :
边栏推荐
- Constructors and prototypes
- Kotlin 常用知识点汇总
- How to set pseudo static for WordPress fixed links
- POI special effects Market Research
- Data broker understanding
- XxE & XML external entity injection utilization and bypass
- LeetCode 0136. 只出现一次的数字:异或
- ratio学习之ratio_add,ratio_subtract,ratio_multiply,ratio_divide的使用
- Discuz magazine / news report template (jeavi_line) utf8 GBK / DZ template download
- How does PHP remove an element from an array based on the key value
猜你喜欢

XxE & XML external entity injection utilization and bypass

Generating random number random learning uniform_ int_ distribution,uniform_ real_ distribution

SAP Message No. VG202 IDoc E1EDK18 中付款条款已经转移:检查数据

chown: changing ownership of ‘/var/lib/mysql/‘: Operation not permitted

Qt风格(QSS)应用之QProgressBar

WebMvcConfigurationSupport

idea设置get、set模板解决boolean类型字段的命名问题

生成随机数random学习之uniform_int_distribution,uniform_real_distribution

Duplicate numbers in array

Learning exploration-3d rotation card
随机推荐
About the foundation of fetch
Serialize addition, deletion, modification and query
日期类的实现
Grain Academy p98 trample pit e.globalexceptionhandler: null
图的遍历-DFS,BFS(代码详解)
谷粒学苑P98踩坑 e.GlobalExceptionHandler : null
Classes and objects (3)
1913. 两个数对之间的最大乘积差-无需排序法
策略模式_
1913. Maximum product difference between two number pairs - no sorting required
Learning exploration - waves
Classes and objects (2) (6 default member functions)
What is the difference between hot deployment and hot loading?
How does Navicat modify the language (Chinese or English)?
Node基础
Generating random number random learning uniform_ int_ distribution,uniform_ real_ distribution
@Autowired annotation required attribute
利用用户脚本优化 Yandere/Konachan 站点浏览体验
PHP wechat scan code, follow official account and authorize login source code
类和对象(2)(6个默认成员函数)