c++11总结14——initializer_list

1. 概念

initializer_list用于表示某种特定类型的值的数组,是一种模板类型。其原型为:

template< class T >         //since c++11
class initializer_list;

2. 使用

2.1 初始化

std::initializer_list<int> lst{ 1,2,3,4,5 };
std::initializer_list<int> lst1(lst);
std::initializer_list<int> lst2 = lst;

cout << lst1.size() << endl; //5
cout << lst2.size() << endl; //5

//std::initializer_list<int> lst4{ 1,2.2,3,"123" }; //error 初始化为int 不能出现double或string

//使用迭代器获取元素
for (auto itr = lst.begin(); itr != lst.end(); ++itr)
	cout << *itr << " " << endl;

for (int i : {1, 2, 3})
{
	cout << i << " ";
}

需要注意的是,initializer_list对象中的元素永远是常量值,我们无法改变initializer_list对象中元素的值。并且,拷贝或赋值一个initializer_list对象不会拷贝列表中的元素,其实只是引用而已,原始列表和副本共享元素。

2.2 在迭代器中使用

可以使用迭代器访问initializer_list中的元素。

void test(std::initializer_list<string> lst)
{
   for(auto itr=lst.begin();itr!=lst.end();++itr)
      cout<<*itr<<endl;  //打印对应的值
   cout<<endl;
}

2.3 优点

方便初始化STL的容器。

3. 使用实例

#include <iostream>
#include <vector>
#include <initializer_list>
using namespace std;

template <class T>
struct S {
	std::vector<T> v;

	S(std::initializer_list<T> l) : v(l) 
	{
		cout << "constructed with a " << l.size() << "-element list"<<endl;
	}

	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[0], v.size() };  
	}
};

template <typename T>
void templated_fn(T) {}

int main()
{
	S<int> s = { 1, 2, 3, 4, 5 }; // copy list-initialization
	s.append({ 6, 7, 8 });      // list-initialization in function call

	cout << "The vector size is now " << s.c_arr().second << " ints:" << endl;

	for (auto n : s.v)
		cout << n << ' ';
	cout << endl;

	cout << "Range-for over brace-init-list: "<<endl;

	for (int x : {-1, -2, -3}) // the rule for auto makes this ranged-for work
		std::cout << x << ' ';
	cout << endl;

	auto al = { 10, 11, 12 };   // special rule for auto

	cout << "The list bound to auto has size() = " << al.size() << endl;

	templated_fn<std::initializer_list<int>>({ 1, 2, 3 }); // OK
	templated_fn<std::vector<int>>({ 1, 2, 3 });

	system("pause");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/www_dong/article/details/113923851