目录
使用目的
1. 一致化的设初值;
2. 接收元素的可变个数
语法
template <class _Elem>
class initializer_list{...};
一般情况下和template作为参数使用 如:
#include <initializer_list>
template<typename T>
void print(initializer_list<T>) {}
示例代码及其讲解
- 初始化值代码演示
int i;
int j{};
int *p;
int *q{}
std::vector<int> v;
v.insert(v.end(), 1);
v.insert(v.end(), 2);
std::vector<int> v{1,2,3};
- 接收元素可变个数代码演示
示例代码1:
#include <iostream>
#include <initializer_list>
template<typename T>
void print(std::initializer_list<T> list)
{
std::cout << "print(initializer_list<T>)" << std::endl;
for(auto i : list)
std::cout << i << std;;endl;
}
int main()
{
print({1,2,3,4,5});
return 0;
}
示例代码2: 需求: 用initializer_list 做参数找到最大值; int max_elem = max({4,2,5,6,8})
struct less_iter_less
{
template<typename iter1, typename iter2>
bool operator()(iter1 iter1_, iter2 iter2_)
{
return *iter1_ < *iter2_;
}
};
template<typename T>
T get_max(T iter1, T iter2, less_iter_less less)
{
if(iter1 == iter2)
return iter1;
T MAX = iter1 ;
while(++iter1 != iter2)
{
if(less(iter1, iter2))
{
MAX = iter2;
}
MAX = iter1;
}
return MAX;
}
template<typename T>
T max_element(T first_iterator, T last_iterator)
{
return get_max(first_iterator, last_iterator, less_iter_less());
}
template<typename T>
T max(std::initializer_list<T> list)
{
return *max_element(list.begin(), list.end());
}
int main()
{
std::cout << max({4,2,5,6,8}) << std::endl;
return 0;
}
以上是我自己在学习过程的一些心得和笔记,如有不当,欢迎指出与批评,感谢观看的各位!
|