Namespaces
Variants

std::forward_list<T,Allocator>:: insert_after

From cppreference.net
iterator insert_after ( const_iterator pos, const T & value ) ;
(1) (自 C++11 起)
(自 C++26 起为 constexpr)
iterator insert_after ( const_iterator pos, T && value ) ;
(2) (自 C++11 起)
(自 C++26 起为 constexpr)
iterator insert_after ( const_iterator pos,
size_type count, const T & value ) ;
(3) (自 C++11 起)
(自 C++26 起为 constexpr)
template < class InputIt >

iterator insert_after ( const_iterator pos,

InputIt first, InputIt last ) ;
(4) (自 C++11 起)
(自 C++26 起为 constexpr)
iterator insert_after ( const_iterator pos,
std:: initializer_list < T > ilist ) ;
(5) (自 C++11 起)
(自 C++26 起为 constexpr)

在容器的指定位置之后插入元素。如果 pos before_begin() ,则插入的第一个元素(如果存在)将成为 * this 的第一个元素。

如果 pos 不在范围 [ before_begin() , end() ) 内,则行为未定义。

1,2) pos 之后插入 value 的副本。
1) 如果 T 不满足 CopyInsertable forward_list 的要求,则行为未定义。
2) 如果 T 不满足 MoveInsertable forward_list 的要求,则行为未定义。
3) pos 之后插入 count value 的副本。
如果 T 不满足 CopyInsertable forward_list 的要求,则行为未定义。
4) pos 之后插入范围 [ first , last ) 中的元素。
此重载仅当 InputIt 满足 LegacyInputIterator 的要求时才参与重载决议。
若满足以下任一条件,则行为未定义:
  • T 无法从 * first 进行 EmplaceConstructible forward_list 中。
  • first last 是指向 * this 的迭代器。
5) pos 之后插入来自初始化列表 ilist 的元素。
等效于 return insert_after ( position, ilist. begin ( ) , ilist. end ( ) ) ;

不会使任何迭代器或引用失效。

目录

参数

pos - 插入位置后的迭代器
value - 要插入的元素值
count - 要插入的副本数量
first, last - 定义要插入元素来源 范围 的迭代器对
ilist - 要插入值的初始化列表

返回值

1,2) 指向被插入元素的迭代器。
3) 指向最后插入元素的迭代器,若 count == 0 true 则返回 pos
4) 指向最后插入元素的迭代器,若 first == last true 则返回 pos
5) 指向最后插入元素的迭代器,若 ilist 为空则返回 pos

异常

若因任何原因抛出异常,这些函数将不产生任何效果( 强异常安全保证 )。

复杂度

1,2) 常量。
3) count 呈线性关系。
4) std:: distance ( first, last ) 呈线性关系。
5) ilist. size ( ) 呈线性关系。

示例

#include <forward_list>
#include <iostream>
#include <string>
#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}

参见

在指定元素后原位构造元素
(公开成员函数)
在容器开头插入元素
(公开成员函数)