当前位置:网站首页>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 :
边栏推荐
- [wechat applet] page navigation
- 学习探索-波浪
- 数组中重复的数字
- LeetCode 0919. 完全二叉树插入器:完全二叉树的数组表示
- Generating random number random learning uniform_ int_ distribution,uniform_ real_ distribution
- [testing technology automated testing pytest] basic summary of pytest
- 在应用中使用 Jetpack 库
- Release of v6.5.1/2/3 series of versions of Xingyun housekeeper: the ability of database OpenAPI continues to be strengthened
- Promise asynchronous callback function
- Solution of phpstudy service environment 80 port occupied by process system under Windows
猜你喜欢

Inheritance (the child constructor inherits the attributes in the parent constructor)

Why are there many snapshot tables in the BI system?

Duplicate numbers in array

Take away applet with main version of traffic / repair to add main access function of traffic

Cuteone: a onedrive multi network disk mounting program / with member / synchronization and other functions

Very simple vsplayaudio online music player plug-in

ES6 syntax (difference between let, const, VaR, deconstruction assignment, arrow function, residual parameters, extension method of array)

动态内存管理

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

意向不到的Dubug妙招
随机推荐
Mongodb update operator (modifier)
物理防火墙是什么?有什么作用?
JS get the current date and time
Discuz magazine / news report template (jeavi_line) utf8 GBK / DZ template download
Classes and objects (2) (6 default member functions)
@Import
Serialize operator
日期类的实现
Very simple vsplayaudio online music player plug-in
Recommended system - an embedded learning framework for numerical features in CTR prediction
Recursion of function (use recursion to find the factorial of 1-N) (use recursion to find Fibonacci sequence) (use recursion to traverse data)
initializer_list工具库学习
[JUC] concurrent keyword volatile
[wechat applet] page navigation
Discuz atmosphere game style template / imitation lol hero League game DZ game template GBK
The difference between MySQL clustered index and non clustered index
Idea sets get and set templates to solve the naming problem of boolean type fields
PyTorch的数据输入格式要求及转换
【微信小程序】页面导航
新手开户选择哪个券商公司好呢?安全吗