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 小时前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛2 天前
delete又未完全delete
c++
端平入洛3 天前
auto有时不auto
c++
郑州光合科技余经理4 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1234 天前
matlab画图工具
开发语言·matlab
dustcell.4 天前
haproxy七层代理
java·开发语言·前端
norlan_jame4 天前
C-PHY与D-PHY差异
c语言·开发语言
哇哈哈20214 天前
信号量和信号
linux·c++
多恩Stone4 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
QQ4022054964 天前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django