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的查找速度快的原因是红黑树的特性,它能保持数据的有序性,并且能进行高效的二分查找。

相关推荐
英英_2 分钟前
python 自动化教程
开发语言·python·自动化
先做个垃圾出来………7 分钟前
汉明距离(Hamming Distance)
开发语言·python·算法
苦学编程的谢7 分钟前
多线程代码案例-1 单例模式
java·开发语言·单例模式
yaoxin52112310 分钟前
80. Java 枚举类 - 使用枚举实现单例模式
java·开发语言·单例模式
hie9889414 分钟前
C#与KepOPC通讯
开发语言·c#
C++ 老炮儿的技术栈18 分钟前
自定义CString类与MFC CString类接口对比
c语言·c++·windows·qt·mfc
kp0000040 分钟前
PHP弱类型安全漏洞解析与防范指南
android·开发语言·安全·web安全·php·漏洞
卡戎-caryon1 小时前
【C++】15.并发支持库
java·linux·开发语言·c++·多线程
90后小陈老师1 小时前
WebXR教学 09 项目7 使用python从0搭建一个简易个人博客
开发语言·python·web
tyatyatya1 小时前
MATLAB 神经网络的系统案例介绍
开发语言·神经网络·matlab