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

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

被折叠的 条评论
为什么被折叠?



