forword_list是C++11新增的一个顺序容器,它是支持从容器的任何位置快速插入和移动元素的容器。不支持快速随机访问。它实现为单链表,且实质上与其在C中实现相比无任何开销。与std::list相比,此容器在不需要 双向迭代时提供更有效地利用空间的存储。下面我们来学习它的 基本用法,首先来看它的创建,初始化,赋值,元素访问front,内容接换swap,判空empty等操作
代码实现:
#include <forward_list>
#include <iostream>
using namespace std;
void createForword_listInit()
{
//1.创建空forword_list
forward_list<int> list1;
cout << "list1.isEmpty = " << list1.empty() << endl;
//2.创建list2有2个元素,值为随机值
forward_list<int> list2(2);
cout << "list2.isEmpty = " << list2.empty() << endl;
cout << "list2的值为:" << endl;
for(auto &val: list2)
{
cout << val << "\t";
}
cout << endl;
//3.创建list3有3个元素,分别为21, 22, 23
forward_list<int> list3 = {21, 22, 23};
cout << "list3.isEmpty = " << list3.empty() << endl;
cout << "list3的值为:" << endl;
for(auto &val: list3)
{
cout << val << "\t";
}
cout << endl;
//4.创建list4,用list3赋值
forward_list<int> list4 = list3;
//forward_list<int> list4(list3);//这两种方法都可以
cout << "list4.isEmpty = " << list4.empty() << endl;
cout << "list4的值为:" << endl;
for(auto &val: list4)
{
cout << val << "\t";
}
cout << endl;
//5.创建list5用assign进行赋值
forward_list<int> list5;
list5.assign({24, 25, 26, 27});
cout << "list5的值为:" << endl;
for(auto &val: list5)
{
cout << val << "\t";
}
cout << endl;
//6.创建list6用list4进行初始化
forward_list<int> list6(list4.begin(), list4.end());
cout << "list6的值为:" << endl;
for(auto &val: list6)
{
cout << val << "\t";
}
cout << endl;
//7.创建list7用assign设定容器大小和初始值
forward_list<int> list7;
list7.assign(5, 18);//list7有5个元素,每个元素为18
cout << "list7的值为:" << endl;
for(auto &val: list7)
{
cout << val << "\t";
}
cout << endl;
//8.访问forward_list
forward_list<int> list8;
list8.assign({28, 28});
cout << "list8.front = " << list7.front() << endl;
cout << "list8的值为:" << endl;
for(auto &val: list8)
{
cout << val << "\t";
}
cout << endl;
//9.swap交换两个forward_list
auto it1 = list6.begin();
auto it2 = list8.begin();
int &ref1 = list6.front();
int &ref2 = list8.front();
cout << "*it1 = " << *it1 << " *it2 = " << *it2 << " ref1 = " << ref1 << " ref2 = " << ref2 << endl;
cout << "swap after======" << endl;
list6.swap(list8);
cout << "list6的值为:" << endl;
for(int c: list6)
{
cout << c << "\t";
}
cout << endl;
cout << "list8的值为:" << endl;
for(int c: list8)
{
cout << c << "\t";
}
cout << endl;
cout << "*it1 = " << *it1 << " *it2 = " << *it2 << " ref1 = " << ref1 << " ref2 = " << ref2 << endl;
cout << endl;
}
int main()
{
createForword_listInit();
cout << endl;
cout << "Hello World!" << endl;
return 0;
}
运行结果:
注意,交换后迭代器与引用保持与原来的元素关联,例如it1指向的元素还是21,ref1引用的元素还21。
参考:
https://zh.cppreference.com/w/cpp/container/forward_list