命名空间
变体
操作

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

来自 cppreference.cn
 
 
 
 
template< class... Args >
iterator emplace_after( const_iterator pos, Args&&... args );
(since C++11)

在容器中指定位置之后的位置插入新元素。元素被就地构造,即不执行复制或移动操作。元素的构造函数使用与函数提供的参数完全相同的参数调用。

没有迭代器或引用会失效。

内容

[edit] 参数

pos - 新元素将在其后构造的迭代器
args - 转发给元素构造函数的参数

[edit] 返回值

指向新元素的迭代器。

[edit] 复杂度

常数。

[edit] 异常

如果由于任何原因抛出异常,此函数不起作用(强异常安全保证)。

[edit] 示例

此示例演示了以自然(相对于反向)顺序规范填充单链表。

#include <forward_list>
#include <iostream>
#include <string>
 
struct Sum
{
    std::string remark;
    int sum;
 
    Sum(std::string remark, int sum)
        : remark{std::move(remark)}, sum{sum} {}
 
    void print() const
    {
        std::cout << remark << " = " << sum << '\n';
    }
};
 
int main()
{
    std::forward_list<Sum> list;
 
    auto iter = list.before_begin();
    std::string str{"1"};
 
    for (int i{1}, sum{1}; i != 10; sum += i)
    {
        iter = list.emplace_after(iter, str, sum);
        ++i;
        str += " + " + std::to_string(i);
    }
 
    for (const Sum& s : list)
        s.print();
}

输出

1 = 1
1 + 2 = 3
1 + 2 + 3 = 6
1 + 2 + 3 + 4 = 10
1 + 2 + 3 + 4 + 5 = 15
1 + 2 + 3 + 4 + 5 + 6 = 21
1 + 2 + 3 + 4 + 5 + 6 + 7 = 28
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 = 36
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 = 45

[edit] 参见

在元素之后插入元素
(public member function) [edit]