std::map看来可以被淘汰了?可以用vector来替代,而且更好

本文比较了C++中std::map与vector在性能上的差异,特别是在插入和查找操作中的内存开销。作者建议在不需要排序且频繁迭代时选择vector,对于需要有序且不常插入的场景,可以选择std::unordered_map。

vector的优势在于内存连续,可以提前申请好。

排序的时候可以用std::sort,可以自己提供排序准则。

查找的时候,可以使用std::lower_bound,或者std::binary_search。

前者可以返回位置,但这个位置所指向的值并不一定和你要查询的值相等。

后者倒是去精准匹配值,只返回bool,查不到就是false,查到了就是true。

而std::map,insert的时候,需要new出节点内存。这些内存不连续。

要是不需要一个排好序的map,仅仅是查询的话,也可以用unordered_map,

来一个lower_bound的例子

#include <algorithm>
#include <vector>
#include <string>

struct Person {
    std::string name;
    int age;
};

// 自定义比较函数
bool compareByAge(const Person& a, const Person& b) {
    return a.age < b.age;
}

int main() {
    std::vector<Person> people = {
        {"Alice", 20},
        {"Bob", 25},
        {"Charlie", 30},
        {"David", 35}
    };
    
    // 查找年龄不小于 28 的人
    Person target = {"", 28};
    auto it = std::lower_bound(people.begin(), people.end(), target, compareByAge);
    
    if (it != people.end()) {
        std::cout << "找到年龄不小于 28 的人: " << it->name 
                  << ", 年龄: " << it->age << std::endl;
    }
    
    return 0;
}

参考:

You may not need std::map - CPP Optimizations diary

原文如下:

Do you actually need to use std::map?

std::map is one of the most known data structures in C++, the default associative container for most of us, but its popularity has been decreasing over the years.

Associative containers are used when you have pairs of key/value and you want to find a value given its

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值