c++map 查找元素和list查找元素速度对比

在C++中,std::map和std::list是两种不同的容器类型,前者是基于红黑树实现的关联容器,后者是双向链表。

如果你想比较这两种容器在查找元素上的速度,通常std::map会比std::list快得多。因为std::map的查找操作是平均常数时间复杂度,即O(log n),而std::list的查找操作是线性时间复杂度,即O(n)。

以下是使用std::map和std::list查找元素的简单示例:

cpp 复制代码
#include <iostream>
#include <map>
#include <list>
#include <string>
#include <chrono>
 
int main() {
    std::map<int, std::string> myMap;
    std::list<std::pair<int, std::string>> myList;
 
    // 填充数据
    for (int i = 0; i < 10000; ++i) {
        myMap[i] = "value" + std::to_string(i);
        myList.push_back(std::make_pair(i, "value" + std::to_string(i)));
    }
 
    // 使用map查找元素
    int keyToFind = 5000;
    auto start = std::chrono::high_resolution_clock::now();
    auto itMap = myMap.find(keyToFind);
    auto end = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double> diff = end - start;
    std::cout << "Find in map: " << diff.count() << " seconds\n";
 
    // 使用list查找元素
    start = std::chrono::high_resolution_clock::now();
    auto itList = std::find_if(myList.begin(), myList.end(), [&](const std::pair<int, std::string>& p) {
        return p.first == keyToFind;
    });
    end = std::chrono::high_resolution_clock::now();
    diff = end - start;
    std::cout << "Find in list: " << diff.count() << " seconds\n";
 
    return 0;
}

在上面的代码中,我们分别在std::map和std::list中查找了一个元素,并记录了查找所需的时间。你可以运行这个程序,并比较两种情况下所需的时间来看出性能上的差异。

请注意,实际情况中,std::list的查找可能会稍慢一些,因为它还需要处理指针操作。而std::map的查找速度快的原因是红黑树的特性,它能保持数据的有序性,并且能进行高效的二分查找。

相关推荐
喵先生!17 分钟前
C++中的vector和list的区别与适用场景
开发语言·c++
Thomas_YXQ1 小时前
Unity3D Lua集成技术指南
java·开发语言·驱动开发·junit·全文检索·lua·unity3d
xMathematics1 小时前
计算机图形学实践:结合Qt和OpenGL实现绘制彩色三角形
开发语言·c++·qt·计算机图形学·cmake·opengl
yuanManGan3 小时前
C++入门小馆: 深入了解STLlist
开发语言·c++
北极的企鹅883 小时前
XML内容解析成实体类
xml·java·开发语言
梁下轻语的秋缘3 小时前
每日c/c++题 备战蓝桥杯(P1049 [NOIP 2001 普及组] 装箱问题)
c语言·c++·学习·蓝桥杯
BillKu3 小时前
Vue3后代组件多祖先通讯设计方案
开发语言·javascript·ecmascript
Python自动化办公社区3 小时前
Python 3.14:探索新版本的魅力与革新
开发语言·python
逐光沧海3 小时前
STL常用算法——C++
开发语言·c++
星火撩猿4 小时前
ubantu中下载编译安装qt5.15.3
开发语言·qt