std::forward_list是可以从任何位置快速插入和移除元素的容器,不支持快速随机访问,只支持正向迭代。
本文章的代码库:
https://gitee.com/gamestorm577/CppStd
成员函数
构造、析构和赋值
构造函数
可以用元素、元素列表、迭代器或者另一个forward_list来构造forward_list。代码示例:
auto print_func = [](const std::forward_list<float>& list)
{
for (auto i : list)
{
std::cout << i << " ";
}
std::cout << std::endl;
};
std::vector<float> vec(10, 1.2f);
std::forward_list<float> f1(4, 3.2f);
std::forward_list<float> f2(4);
std::forward_list<float> f3(vec.begin(), vec.end());
std::forward_list<float> f4(f1);
std::forward_list<float> tmp(f1);
std::forward_list<float> f5(std::move(tmp));
std::forward_list<float> f6{1.f, 2.f, 3.f};
print_func(f1);
print_func(f2);
print_func(f3);
print_func(f4);
print_func(f5);
print_func(f6);
输出结果:
3.2 3.2 3.2 3.2
0 0 0 0
1.2 1.2 1.2 1.2 1.2 1.2 1.2 1.2 1.2 1.2
3.2 3.2 3.2 3.2
3.2 3.2 3.2 3.2
1 2 3
析构函数
forward_list析构时,会按照正向顺序依次删除元素。代码示例:
struct MyStruct
{
MyStruct(int i)
: Index(i)
{
}
~MyStruct()
{
std::cout << "destruct, Index = " << Index << std::endl;
}
int Index = 0;
};
std::forward_list<MyStruct> f;
f.emplace_front(1);
f.emplace_front(3);
f.emplace_front(5);
输出结果:
destruct, Index = 5
destruct, Index = 3
destruct, Index = 1
赋值函数
可以用元素列表或者另一个forward_list赋值给forward_list。代码示例:
auto print_func = [](const std::forward_list<float>& list)
{
for (auto i : list)
{
std::cout << i << " ";
}
std::cout << std::endl;
};
std::forward_list<float> tmp = {1.1f, 2.1f, 3.1f};
std::forward_list<float> f1;
std::forward_list<float> f2;
f1 = tmp;
f2 = {2.1f, 2.2f, 2.3f, 2.4f};
print_func(f1);
print_func(f2);
输出结果:
1.1 2.1 3.1
2.1 2.2 2.3 2.4
assign
将值赋值给forward_list,可以是元素、元素列表或者迭代器。代码示例:
auto print_func = [](const std::forward_list<float>& list)
{
for (auto i : list)
{
std::cout << i << " ";
}
std::cout << std::endl;
};
std::vector<float> vec(10, 1.2f);
std::forward_list<float> f;
f.assign(5, 1.2);
print_func(f);
f.assign(vec.begin(), vec.end());
print_func(f);
f.assign({1.1f, 2.1f, 3.1f});
print_func(f);
输出结果:
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::forward_list<float> f = {1.f, 2.f, 3.f};
f.