std::forward_list<T,Allocator>::insert_after
来自cppreference.com
| |
(1) | (C++11 起) |
| |
(2) | (C++11 起) |
| |
(3) | (C++11 起) |
| |
(4) | (C++11 起) |
| |
(5) | (C++11 起) |
在容器中的指定位置后插入元素。
1-2) 在
pos 所指向的元素后插入 value。3) 在
pos 所指向的元素后插入 value 的 count 个副本。4) 在
pos 所指向的元素后插入来自范围 [first, last) 的元素。
若 first 与 last 是指向 *this 中的迭代器则行为未定义。5) 插入来自 initializer_list
ilist 的元素。没有引用和迭代器会失效。
参数
| pos | - | 内容将插入到其后的迭代器 |
| value | - | 要插入的元素值 |
| count | - | 要插入的副本数 |
| first, last | - | 要插入的源元素范围的迭代器对 |
| ilist | - | 插入值来源的初始化式列表 |
| 类型要求 | ||
-InputIt 必须满足老式输入迭代器 (LegacyInputIterator) 。
| ||
返回值
1,2) 指向被插入元素的迭代器。
3) 指向最后被插入元素的迭代器,或若
count==0 则为 pos。4) 指向最后被插入元素的迭代器,或若
first==last 则为 pos。5) 指向最后被插入元素的迭代器,或若
ilist 为空则为 pos。异常
如果因为任何原因抛出了异常,那么这些函数无效果(强异常安全保证)。
复杂度
1,2) 常数。
3) 与
count 成线性。4) 与
std::distance(first, last) 成线性。5) 与
ilist.size() 成线性。示例
运行此代码
#include <forward_list>
#include <string>
#include <iostream>
#include <vector>
void print(const std::forward_list<int>& list)
{
std::cout << "list: {";
for (char comma[3] = {'\0', ' ', '\0'}; int i : list)
{
std::cout << comma << i;
comma[0] = ',';
}
std::cout << "}\n";
}
int main()
{
std::forward_list<int> ints{1, 2, 3, 4, 5};
print(ints);
// insert_after (2)
auto beginIt = ints.begin();
ints.insert_after(beginIt, -6);
print(ints);
// insert_after (3)
auto anotherIt = beginIt;
++anotherIt;
anotherIt = ints.insert_after(anotherIt, 2, -7);
print(ints);
// insert_after (4)
const std::vector<int> v = {-8, -9, -10};
anotherIt = ints.insert_after(anotherIt, v.cbegin(), v.cend());
print(ints);
// insert_after (5)
ints.insert_after(anotherIt, {-11, -12, -13, -14});
print(ints);
}
输出:
list: {1, 2, 3, 4, 5}
list: {1, -6, 2, 3, 4, 5}
list: {1, -6, -7, -7, 2, 3, 4, 5}
list: {1, -6, -7, -7, -8, -9, -10, 2, 3, 4, 5}
list: {1, -6, -7, -7, -8, -9, -10, -11, -12, -13, -14, 2, 3, 4, 5}
参阅
| 在元素后原位构造元素 (公开成员函数) | |
| 插入元素到容器起始 (公开成员函数) |