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

相关推荐
睡美人的小仙女1275 小时前
Threejs加载环境贴图报错Bad File Format: bad initial token
开发语言·javascript·redis
rayufo5 小时前
【工具】列出指定文件夹下所有的目录和文件
开发语言·前端·python
RANCE_atttackkk5 小时前
[Java]实现使用邮箱找回密码的功能
java·开发语言·前端·spring boot·intellij-idea·idea
缺点内向6 小时前
C#编程实战:如何为Word文档添加背景色或背景图片
开发语言·c#·自动化·word·.net
一起养小猫6 小时前
Flutter for OpenHarmony 实战:记账应用数据统计与可视化
开发语言·jvm·数据库·flutter·信息可视化·harmonyos
zhougl9966 小时前
Java 所有关键字及规范分类
java·开发语言
java1234_小锋6 小时前
Java高频面试题:MyISAM索引与InnoDB索引的区别?
java·开发语言
2501_944525546 小时前
Flutter for OpenHarmony 个人理财管理App实战 - 支出分析页面
android·开发语言·前端·javascript·flutter
Bella的成长园地6 小时前
面试中关于 c++ async 的高频面试问题有哪些?
c++·面试
彷徨而立7 小时前
【C/C++】什么是 运行时库?运行时库 /MT 和 /MD 的区别?
c语言·c++