c++ - std::set::emplace_hint() 实际上如何加速插入过程?
问题描述
我不明白(尽管有评论)emplace_hint() 函数是如何工作的,emplace_hint() 实际上如何加快插入过程?有人可以解释一下代码吗?
// CPP program to demonstrate the
// set::emplace_hint() function
#include <iostream>
#include <set>
using namespace std;
int main()
{
set<int> s;
auto it = s.emplace_hint(s.begin(), 1);
/* stores the position of 2's insertion*/
it = s.emplace_hint(it, 2);
/* fast step as it directly
starts the search step from
position where 3 was last inserted */
s.emplace_hint(it, 3);
/* this is a slower step as
it starts checking from the
position where 3 was inserted
but 0 is to be inserted before 1 */
s.emplace_hint(it, 0);
/* prints the set elements*/
for (auto it = s.begin(); it != s.end(); it++)
cout << *it << " ";
return 0;
}
解决方案
std::set
通常实现为平衡二叉搜索树。通常,set::insert
需要搜索树来为新元素找到合适的插入点,这需要O(log N)
时间。但是如果调用者可以提供一个正确的插入点——即,一个与新元素相邻的现有元素的迭代器——那么可以避免这种搜索,并且可以在 O(1) 时间内完成插入。
emplace_hint
让调用者有机会提供该迭代器。
推荐阅读
- python - 如何在 PySimpleGUI 中清除窗口
- django - 如何使用 Django REST 和 React.js 关系处理 CSRFToken 真实性?
- javascript - React Axios 从一个操作创建多个请求
- python - 使用 Selenium 启动 IE 后超时
- reactjs - 在 React 中提交表单后呈现错误消息
- swift - 滚动后为 UITableView 顶部的第一个可见单元格着色
- python - 破译 Python Mypy 报告
- javascript - 带有 readline nodejs 的 Sycn 输入
- python - 通过 Python 和 ruamel.yaml 模块编辑 YAML 文件
- spring-boot - 如何将额外的参数从 html 传递到控制器