std::set<Key,Compare,Allocator>::insert
来自cppreference.com
| std::pair<iterator,bool> insert( const value_type& value ); |
(1) | |
| std::pair<iterator,bool> insert( value_type&& value ); |
(2) | (C++11 起) |
| (3) | ||
| iterator insert( iterator hint, const value_type& value ); |
(C++11 前) | |
| iterator insert( const_iterator hint, const value_type& value ); |
(C++11 起) | |
| iterator insert( const_iterator hint, value_type&& value ); |
(4) | (C++11 起) |
| template< class InputIt > void insert( InputIt first, InputIt last ); |
(5) | |
| void insert( std::initializer_list<value_type> ilist ); |
(6) | (C++11 起) |
| insert_return_type insert(node_type&& nh); |
(7) | (C++17 起) |
| iterator insert(const_iterator hint, node_type&& nh); |
(8) | (C++17 起) |
插入元素到容器,若容器未含拥有等价关键的元素。
1-2) 插入
value 。3-4) 插入
value 到尽可能接近,正好前于(C++11 起) hint 的位置。7) 若
nh 是空的结点把柄,则不做任何事。否则插入 nh 所占有的元素到容器,若容器尚未含有拥有等价于 nh.key() 的关键的元素。若 nh 非空且 get_allocator() != nh.get_allocator() 则行为未定义。8) 若
nh 是空的结点把柄,则不做任何事并返回尾迭代器。否则,插入 nh 所占有的元素到容器,若容器尚未含有拥有等价于 nh.key() 的关键的元素,并返回指向拥有等于 nh.key() 的关键的元素的迭代器(无关乎插入成功还是失败)。若插入成功,则从 nh 移动,否则它保持该元素的所有权。元素被插入到尽可能接近正好先于 hint 的位置。若 nh 非空且 get_allocator() != nh.get_allocator() 则行为未定义。没有迭代器或引用被非法化。若插入成功,则在结点把柄保有元素时获得的指向该元素的指针和引用被非法化,而在提取前获得的指向元素的指针和引用变得合法。 (C++17 起)
参数
| hint | - |
| ||||
| value | - | 要插入的元素值 | ||||
| first, last | - | 要插入的元素范围 | ||||
| ilist | - | 插入值来源的 initializer_list | ||||
| nh | - | 兼容的结点把柄 | ||||
| 类型要求 | ||||||
-InputIt 必须满足遗留输入迭代器 (LegacyInputIterator) 的要求。
| ||||||
返回值
1-2) 返回由指向被插入元素(或阻止插入的元素)的迭代器和若插入发生则设为 true 的 bool 值。
3-4) 返回指向被插入元素,或阻止插入的元素的迭代器。
5-6) (无)
7) 返回
insert_return_type ,其成员初始化如下:若 nh 为空,则 inserted 为 false , position 为 end() ,而 node 为空。否则发生插入, inserted 为 true , position 指向被插入元素,而 node 为空。若插入失败,则 inserted 为 false , node 拥有 nh 的先前值,而 position 指向拥有等价于 nh.key() 的关键的元素。8) 若
nh 为空则为尾迭代器,若插入发生则为指向被插入元素的迭代器,而若插入失败则为指向拥有等价于 nh.key() 的关键的元素的迭代器。异常
1-4) 若任何操作抛异常,则插入无效果。
| 本节未完成 原因:情况 5-8 |
复杂度
1-2) 与容器大小成对数,
O(log(size())) 。|
3-4) 若插入恰好发生在正好后于 hint 的位置,则为均摊常数,否则与容器大小成对数。
|
(C++11 前) |
|
3-4) 若插入恰好发生在正好先于 hint 的位置,则为均摊常数,否则与容器大小成对数。
|
(C++11 起) |
5-6)
O(N*log(size() + N)) ,其中 N 是要插入的元素数。7) 与容器大小成对数,
O(log(size())) 。8) 若插入恰好发生在正好先于 hint 的位置,则为均摊常数,否则与容器大小成对数。
注意
有提示插入 (3,4) 不返回 bool ,这是为了与顺序容器上的定位插入,如 std::vector::insert 签名兼容。这使得可以创建泛型插入器,例如 std::inserter 。检查有提示插入是否成功的一种方式是比较插入前后的 size() 。
重载 (5,6) 通常实现为循环,其中以 end() 为 hint 调用重载 (3) ;它们对后附最小元素大于 *this 中最大元素的有序序列(例如另一 set )优化。
示例
运行此代码
#include <set> #include <cassert> #include <iostream> int main() { std::set<int> set; auto result_1 = set.insert(3); assert(result_1.first != set.end()); // 它是合法迭代器 assert(*result_1.first == 3); if (result_1.second) std::cout << "insert done\n"; auto result_2 = set.insert(3); assert(result_2.first == result_1.first); // 相同迭代器 assert(*result_2.first == 3); if (!result_2.second) std::cout << "no insertion\n"; }
输出:
insert done no insertion
参阅
| (C++11) |
原位构造元素 (公开成员函数) |
| (C++11) |
使用提示原位构造元素 (公开成员函数) |