将pair添加到映射的末尾
C++ map: add pair to the end of the map
我正试图找到一种更快的方法来将配对添加到地图的末尾。目前,我在映射的末尾添加对,因为我使用的键是默认排序的for循环的索引。输入:
#include <algorithm>
#include <iostream>
#include <vector>
#include <map>
#include <set>
int main()
{
std::map<int, std::set<int> > temp;
for(int i = 0; i < 1000000; i++){
int first[] = {5,10,15,20,25};
int second[] = {10,20,30,40,50};
std::set<int> temp2;
temp2.insert(first, first + 5);
std::set<int> temp3;
temp3.insert(second, second + 5);
std::set<int> temp4;
std::set_union(temp2.begin(), temp2.end(), temp3.begin(), temp3.end(), std::inserter(temp4, temp4.end()));
temp.insert(temp.end(), std::pair<int, std::set<int> >(i, temp4));
}
}
当我计时时,大约需要10秒。但是,当我注释掉temp.insert(temp.end(), std::pair<int, std::set<int> >(i, temp4))
行时,程序大约需要4秒钟才能执行。我想知道为什么把这对添加到地图上要花这么多时间。我是不是用了最好的方法?
对于初学者来说,这不仅仅是一对微不足道的小对。它是一个包含整个容器的pair。
虽然是一个小容器。但是它已经被填充了,并且将它插入到另一个容器的行为意味着需要复制整个容器。
但更重要的是,std::map
不是具有平摊常数插入复杂度的向量。它通常是平衡树的某种变体,在大多数c++实现中通常是红黑树。
这意味着在地图的最后重复insert()
s,无论是否暗示,通常都需要重新平衡整个树。这不是一项廉价的手术。而且,通过反复插入总是在键空间末尾排序的键,可怜的映射必须不断地重新平衡自己,一次又一次。
相关文章:
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 将函数类成员映射到类本身内部
- 如何在 C# 中映射双 C 结构指针?
- 如何在C++中使用结构生成映射
- 使用std::函数映射对象方法
- 如何加载(或映射)文件部分的最大大小,但适合在Windows上的RAM
- 是否需要删除包含对象的"pair"?
- C++映射分割错误(核心转储)
- 内联映射初始化的动态atexit析构函数崩溃
- 使用"std::unordereded_map"映射到"std::list"对象
- 将从std::映射中获取的std::pair引用传递给接受std::对引用的函数
- 如何使用迭代器遍历表单 pair<int,pair<int,int>> 的映射
- 获取C++中形式为 <pair<int,int>, int*> 的映射的所有键
- 添加多个元素以映射<pair> c++
- 它无法将 c++ 映射结构编译为 map<A、pair<B、C> >
- Pair(const std::p air<_T1, _T2>&) 被隐式删除,因为默认定义格式不正确 错误:分配unique_ptr映射时
- 将pair添加到映射的末尾
- 映射和节点,错误智能感知:不存在从"const std::pair<const int, double>"到"Node"的合适用户定义转换
- 对无序映射的pair对象的第一部分解引用