std::forward_list是可以从任何位置快速插入和移除元素的容器,不支持快速随机访问,支持正向和反向的迭代。
本文章的代码库:
https://gitee.com/gamestorm577/CppStd
成员函数
构造、析构和赋值
构造函数
可以用元素、元素列表、迭代器或者另一个list来构造list。代码示例:
auto print_func = [](const std::list<float>& list)
{
for (auto i : list)
{
std::cout << i << " ";
}
std::cout << std::endl;
};
std::vector<float> vec{1.1f, 2.1f, 3.1f};
std::list<float> l1(5, 1.1f);
std::list<float> l2(5);
std::list<float> l3(vec.begin(), vec.end());
std::list<float> l4(l1);
std::list<float> tmp(l1);
std::list<float> l5(std::move(tmp));
std::list<float> l6{11.1f, 12.1, 13.1f};
print_func(l1);
print_func(l2);
print_func(l3);
print_func(l4);
print_func(l5);
print_func(l6);
输出结果:
1.1 1.1 1.1 1.1 1.1
0 0 0 0 0
1.1 2.1 3.1
1.1 1.1 1.1 1.1 1.1
1.1 1.1 1.1 1.1 1.1
11.1 12.1 13.1
析构函数
list析构时,会按照正向顺序依次删除元素。代码示例:
struct MyStruct
{
MyStruct(int i)
: Index(i)
{
}
~MyStruct()
{
std::cout << "destruct, Index = " << Index << std::endl;
}
int Index = 0;
};
std::list<MyStruct> l;
l.emplace_front(1);
l.emplace_front(3);
l.emplace_front(5);
输出结果:
destruct, Index = 5
destruct, Index = 3
destruct, Index = 1
赋值函数
可以用元素列表或者另一个list赋值给forward_list。代码示例:
auto print_func = [](const std::list<float>& list)
{
for (auto i : list)
{
std::cout << i << " ";
}
std::cout << std::endl;
};
std::list<float> tmp = {1.1f, 2.1f, 3.1f};
std::list<float> l1;
std::list<float> l2;
l1 = tmp;
l2 = {2.1f, 2.2f, 2.3f, 2.4f};
print_func(l1);
print_func(l2);
输出结果:
1.1 2.1 3.1
2.1 2.2 2.3 2.4
assign
将值赋值给forward_list,可以是元素、元素列表或者迭代器。代码示例:
auto print_func = [](const std::list<float>& list)
{
for (auto i : list)
{
std::cout << i << " ";
}
std::cout << std::endl;
};
std::vector<float> vec(10, 1.2f);
std::list<float> l;
l.assign(5, 1.2);
print_func(l);
l.assign(vec.begin(), vec.end());
print_func(l);
l.assign({1.1f, 2.1f, 3.1f});
print_func(l);
输出结果:
1.2 1.2 1.2 1.2 1.2
1.2 1.2 1.2 1.2 1.2 1.2 1.2 1.2 1.2 1.2
1.1 2.1 3.1
元素访问
front
返回首个元素的引用。示例代码:
std::list<float> l = {1.f, 2.f, 3.f};
l.front() = 4.1f;
std::cout << "l front is: " << l.front() << std::endl;
输出结果:
l front is: 4.1
back
返回最后一个元素的引用。示例代码:
std::list<float> l = {1.f, 2.f, 3.f};
l.back() = 24.1f;
std::cout << "l back is: " << l.back() << std::endl;
输出结果: