定义于头文件 <list>
template< class T, class Allocator = std::allocator<T> > class list; (1)
namespace pmr { template <class T>
using list = std::list<T, std::pmr::polymorphic_allocator<T>>;} (2) (C++17 起)
std::list 是支持常数时间从容器任何位置插入和移除元素的容器。不支持快速随机访问。它通常实现为双向链表。与 std::forward_list 相比,此容器提供双向迭代但在空间上效率稍低。
在 list 内或在数个 list 间添加、移除和移动元素不会非法化迭代器或引用。迭代器仅在对应元素被删除时非法化。
std::list 满足容器 (Container) 、具分配器容器 (AllocatorAwareContainer) 、序列容器 (SequenceContainer) 及可逆容器 (ReversibleContainer) 的要求。
插入元素到容器起始
std::list<T,Allocator>::push_front
void push_front( const T& value ); | ||
void push_front( T&& value ); | (C++11 起) |
前附给定元素 value
到容器起始。
没有引用和迭代器被非法化。
参数
value | - | 要前附的元素值 |
返回值
(无)
复杂度
常数。
异常
若抛出异常,则此函数无效果(强异常保证)。
调用示例
#include <list>
#include <iostream>
#include <iomanip>
int main()
{
std::list<std::string> numbers;
numbers.push_front("abc");
std::string s = "def";
std::cout << "Moved-from string before \"" << s << "\"\n";
numbers.push_front(std::move(s));
std::cout << "list holds: ";
for (auto&& number : numbers)
{
std::cout << "\"" << number << "\" ";
}
std::cout << "\nMoved-from string holds \"" << s << "\"\n";
}
输出
在容器头部就地构造元素
std::list<T,Allocator>::emplace_front
template< class... Args > | (C++11 起) (C++17 前) | |
template< class... Args > | (C++17 起) |
插入新元素到容器起始。通过 std::allocator_traits::construct 构造元素,它典型地用布置 new 在容器所提供的位置原位构造元素。将参数 args...
作为 std::forward<Args>(args)... 转发给构造函数。
没有引用和迭代器被非法化。
参数
args | - | 转发给元素构造函数的参数 |
类型要求 | ||
- T (容器元素类型) 必须满足可就位构造 (EmplaceConstructible) 的要求。 |
返回值
(无) | (C++17 前) |
到被插入元素的引用。 | (C++17 起) |
复杂度
常数。
异常
若抛异常,则此函数无效果(强异常保证)。
调用示例
#include <list>
#include <string>
#include <iostream>
struct President
{
std::string name;
std::string country;
int year;
President(std::string p_name, std::string p_country, int p_year)
: name(std::move(p_name)), country(std::move(p_country)), year(p_year)
{
std::cout << "I am being constructed.\n";
}
President(President&& other)
: name(std::move(other.name)), country(std::move(other.country)), year(other.year)
{
std::cout << "I am being moved.\n";
}
President& operator=(const President& other) = default;
};
int main()
{
std::list<President> elections;
std::cout << "emplace_back:\n";
elections.emplace_front("Nelson Mandela", "South Africa", 1994);
std::list<President> reElections;
std::cout << "\npush_back:\n";
reElections.push_front(President("Franklin Delano Roosevelt", "the USA", 1936));
std::cout << "\nContents:\n";
for (President const& president : elections)
{
std::cout << president.name << " was elected president of "
<< president.country << " in " << president.year << ".\n";
}
for (President const& president : reElections)
{
std::cout << president.name << " was re-elected president of "
<< president.country << " in " << president.year << ".\n";
}
}