C++ 有序插入到stl::map是否更快?

C++ 有序插入到stl::map是否更快?,c++,stl,containers,C++,Stl,Containers,由于stl::map是一个有序映射,插入排序数据集会更快吗?特别是如果我们考虑一个大的数据集, < P>当然,已经排序了数据。 #include <map> #include <vector> int main() { std::vector<int> data { 0, 1, 2, 3, 4, 5 }; std::map<int, int> result; // From: http://en.cppreference.

由于
stl::map
是一个有序映射,插入排序数据集会更快吗?特别是如果我们考虑一个大的数据集,

< P>当然,已经排序了数据。
#include <map>
#include <vector>

int main() {
    std::vector<int> data { 0, 1, 2, 3, 4, 5 };
    std::map<int, int> result;
    // From: http://en.cppreference.com/w/cpp/container/map/insert
    // Amortized constant if the insertion happens in the position just before
    // the hint, logarithmic in the size of the container otherwise.
    for(auto i : data)
        result.insert(result.end(), { i, i} );
}
#包括
#包括
int main(){
向量数据{0,1,2,3,4,5};
映射结果;
//发件人:http://en.cppreference.com/w/cpp/container/map/insert
//如果插入发生在之前的位置,则摊销常数
//提示,否则容器的大小为对数。
用于(自动i:数据)
insert(result.end(),{i,i});
}

当然可以,已排序数据

#include <map>
#include <vector>

int main() {
    std::vector<int> data { 0, 1, 2, 3, 4, 5 };
    std::map<int, int> result;
    // From: http://en.cppreference.com/w/cpp/container/map/insert
    // Amortized constant if the insertion happens in the position just before
    // the hint, logarithmic in the size of the container otherwise.
    for(auto i : data)
        result.insert(result.end(), { i, i} );
}
#包括
#包括
int main(){
向量数据{0,1,2,3,4,5};
映射结果;
//发件人:http://en.cppreference.com/w/cpp/container/map/insert
//如果插入发生在之前的位置,则摊销常数
//提示,否则容器的大小为对数。
用于(自动i:数据)
insert(result.end(),{i,i});
}

是的,没错。从大O的角度来看,逐个插入N个元素就是O(N*logN),相比之下,构建一个映射(通常是某种平衡的二叉树)只需要O(N)

您还可以参考GCC的libstdc++实现。

是的,没错。从大O的角度来看,逐个插入N个元素就是O(N*logN),相比之下,构建一个映射(通常是某种平衡的二叉树)只需要O(N)

您还可以参考GCC的libstdc++实现。

为什么不试试看呢?我想这取决于具体的实现<代码>地图
通常使用某种树结构-红黑树或AVL树或类似的树。插入已排序的序列仍然会每隔一段时间触发重新平衡,这是影响插入性能的唯一因素。这就是说,可能有一些神奇的序列不会触发重新平衡或触发频率较低。不一定是经过排序的序列。@WhiZTiM:性能的第二条规则,“永远不要只依赖于在一台机器上测量的结果”。std:::map::insert(在本例中应该是std::map::end())中有提示,使插入摊销不变。@DieterLücking很好。为什么不试试看呢?我认为这取决于具体的实现<代码>地图通常使用某种树结构-红黑树或AVL树或类似的树。插入已排序的序列仍然会每隔一段时间触发重新平衡,这是影响插入性能的唯一因素。这就是说,可能有一些神奇的序列不会触发重新平衡或触发频率较低。不一定是经过排序的序列。@WhiZTiM:性能的第二条规则,“永远不要依赖于在一台机器上测量的结果”。std:::map::insert(在本例中应该是std::map::end())中有提示,使插入摊销为常量。@DieterLücking Good catch。