名稱空間
變體
操作

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

來自 cppreference.com
< cpp‎ | 容器‎ | forward_list
 
 
 
 
template< class... Args >
iterator emplace_after( const_iterator pos, Args&&... args );
(C++11 起)

在容器中指定位置之後插入一個新元素。該元素在原位構造,即不執行復制或移動操作。元素的建構函式將使用與提供給函式完全相同的引數呼叫。

迭代器或引用均未失效。

目錄

[編輯] 引數

pos - 將在其後構造新元素的迭代器
args - 轉發給元素建構函式的引數

[編輯] 返回值

指向新元素的迭代器。

[編輯] 複雜度

常數時間。

[編輯] 異常

如果由於任何原因丟擲異常,此函式無效果(強異常安全保證)。

[編輯] 示例

該示例演示了以自然(而非逆序)順序填充單鏈表的規範方法。

#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

[編輯] 另請參閱

在元素之後插入元素
(public member function) [編輯]