将pair添加到映射的末尾

C++ map: add pair to the end of the map

本文关键字:映射 pair 添加      更新时间:2023-10-16

我正试图找到一种更快的方法来将配对添加到地图的末尾。目前,我在映射的末尾添加对,因为我使用的键是默认排序的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,无论是否暗示,通常都需要重新平衡整个树。这不是一项廉价的手术。而且,通过反复插入总是在键空间末尾排序的键,可怜的映射必须不断地重新平衡自己,一次又一次。