c++ - map insert(const_iterator hint, value) 用法

标签 c++

我正在浏览 cppreference map insert operation 并找到一个用法:

iterator insert( const_iterator hint, const value_type& value ); //(since C++11)

hint: iterator to the position before which the new element will be inserted (since C++11)

我知道 mapset 是内部排序的,那么“在提示后立即插入”的用法如何工作?

测试代码:

#include <set>
using namespace std;
int main()
{
    set<int> foo = { 9,2,4,8,0 }; //0,2,4,8,9
    //foo.insert(-1); //-1,0,2,4,8,9

    const auto pos = foo.find(4);
    foo.insert(pos, -1); //I expected to get 0,2,4,-1,8,9
                        //(unreasonable since map should be always sorted but that's how I understand the function usage)
                       // And I got -1,0,2,4,8,9  same result as insert(value)

}

insert(const_iterator hint, value) 是如何工作的?

最佳答案

您传递的迭代器“只是”一个提示,这意味着如果提示错误,该函数将回退到常规插入。

如果提示正确,插入将在分摊的常数时间内发生,但如果错误,它将在 map 或 set 的大小上呈对数。

查看在 llvm stdlib 中是如何完成的:https://github.com/llvm-mirror/libcxx/blob/master/include/map

关于c++ - map insert(const_iterator hint, value) 用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51202119/

相关文章:

c++ - 几个线程的多个任务

c++ - 如何设置浮点值的格式,使其从不使用指数表示法或尾随零?

c++ - 将 Cpp 代码片段转换为 VB.NET

c++ - 在 C++ 中使用类对复数进行加减法运算

c++ - 在不同的完整路径下用 C++ 保存文件

c++ - 使用抽象来制作翻译器

c++ - BGL - 使用具有捆绑属性的流算法

c++ - 新的没有分配足够的内存?

c++,在二维空间中生成均匀分布的菱形或三角形孔

c++ - If/else 循环 : C++ Program: Won't display final prompt/final loop