跳到主要内容

std::forward_list emplace_after() 方法

// Non const version only
template< class... Args >
iterator emplace_after( const_iterator pos, Args&&... args );

在容器中指定的节点之后插入一个新元素。

元素原地构造,即不执行拷贝或移动操作。元素的构造函数将使用与函数相同的参数调用。

参数

  • pos - 新元素将被构造在其之前的位置的迭代器
  • args - 转发给元素构造函数的参数

返回值

指向新元素的迭代器。

复杂度

常数 - O(1)

异常

如果任何操作抛出异常,则不会有任何影响(强异常保证)。

示例

Main.cpp
#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
本文来源于 此 CppReference 页面。可能已根据改进或编辑偏好进行了修改。点击“编辑此页”查看对本文档的所有更改。
悬停查看原始许可证。

std::forward_list emplace_after() 方法

// Non const version only
template< class... Args >
iterator emplace_after( const_iterator pos, Args&&... args );

在容器中指定的节点之后插入一个新元素。

元素原地构造,即不执行拷贝或移动操作。元素的构造函数将使用与函数相同的参数调用。

参数

  • pos - 新元素将被构造在其之前的位置的迭代器
  • args - 转发给元素构造函数的参数

返回值

指向新元素的迭代器。

复杂度

常数 - O(1)

异常

如果任何操作抛出异常,则不会有任何影响(强异常保证)。

示例

Main.cpp
#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
本文来源于 此 CppReference 页面。可能已根据改进或编辑偏好进行了修改。点击“编辑此页”查看对本文档的所有更改。
悬停查看原始许可证。