std::forward_list insert_after() 方法
- 自 C++11 起
// (1) Non const version only
iterator insert( const_iterator pos, const T& value );
// (2) Non const version only
iterator insert( const_iterator pos, T&& value );
// (3) Non const version only
iterator insert( const_iterator pos, size_type count, const T& value );
// (4) Non const version only
template< class InputIt >
iterator insert( const_iterator pos, InputIt first, InputIt last );
// (5) Non const version only
iterator insert( const_iterator pos, std::initializer_list<T> ilist );
在容器中指定的元素之后插入元素。
- (1-2) 在
pos
之前插入value
。 - (3) 在
pos
指向的元素之后插入count
个value
的副本。 - (4) 在
pos
指向的元素之后插入范围 [ first, last ) 中的元素。未定义行为如果
first
和last
是指向*this
的迭代器,则行为未定义。 - (5) 插入初始化列表
ilist
中的元素。
参数
pos
- 将在其后插入内容的迭代器value
- 要插入的元素值count
- 要插入的元素数量first
,last
- 要插入的元素范围ilist
- 要从中插入值的初始化列表
类型要求
- (4) -
InputIt
必须满足LegacyInputIterator
的要求。
返回值
- (1-2) 指向插入值的迭代器。
- (3) 指向最后一个插入元素的迭代器,如果
count == 0
则为pos
。 - (4) 指向最后一个插入元素的迭代器,如果
first == last
则为pos
。 - (5) 指向最后一个插入元素的迭代器,如果
ilist
为空则为pos
。
复杂度
- (1-2) 常数 - O(1)。
- (3) 线性于
count
- O(count)。 - (4) 线性于
std::distance(first, last)
- O(std::distance(first, last))。 - (5) 线性于
ilist.size()
- O(ilist.size())。
异常
如果任何操作抛出异常,则没有影响(强异常保证)。
示例
Main.cpp
#include <forward_list>
#include <string>
#include <iostream>
#include <vector>
template<typename T>
std::ostream& operator<<(std::ostream& s, const std::forward_list<T>& v) {
s.put('[');
char comma[3] = {'\0', ' ', '\0'};
for (const auto& e : v) {
s << comma << e;
comma[0] = ',';
}
return s << ']';
}
int main()
{
std::forward_list<std::string> words {"the", "frogurt", "is", "also", "cursed"};
std::cout << "words: " << words << '\n';
// insert_after (2)
auto beginIt = words.begin();
words.insert_after(beginIt, "strawberry");
std::cout << "words: " << words << '\n';
// insert_after (3)
auto anotherIt = beginIt;
++anotherIt;
anotherIt = words.insert_after(anotherIt, 2, "strawberry");
std::cout << "words: " << words << '\n';
// insert_after (4)
std::vector<std::string> V = { "apple", "banana", "cherry"};
anotherIt = words.insert_after(anotherIt, V.begin(), V.end());
std::cout << "words: " << words << '\n';
// insert_after (5)
words.insert_after(anotherIt, {"jackfruit", "kiwifruit", "lime", "mango"});
std::cout << "words: " << words << '\n';
}
输出
words: [the, frogurt, is, also, cursed]
words: [the, strawberry, frogurt, is, also, cursed]
words: [the, strawberry, strawberry, strawberry, frogurt, is, also, cursed]
words: [the, strawberry, strawberry, strawberry, apple, banana, cherry, frogurt, is, also, cursed]
words: [the, strawberry, strawberry, strawberry, apple, banana, cherry, jackfruit, kiwifruit, lime, mango, frogurt, is, also, cursed]