map: map内部实现了一个红黑树,该结构具有自动排序的功能,因此map内部的所有元素都是有序的,红黑树的每一个节点都代表着map的一个元素,因此,对于map进行的查找,删除,添加等一系列的操作都相当于是对红黑树进行这样的操作,故红黑树的效率决定了map的效率。
unordered_map: unordered_map内部实现了一个哈希表,因此其元素的排列顺序是杂乱的,无序的。
// 示例代码(基于时间的键值存储)
class TimeMap {
public:
/** Initialize your data structure here. */
unordered_map<string, map<int, string>> mapLive;
TimeMap() {
}
void set(string key, string value, int timestamp) {
mapLive[key][timestamp] = value;
}
string get(string key, int timestamp) {
if ((mapLive[key].size() == 0) || (mapLive[key].upper_bound(timestamp) == mapLive[key].begin())) {
return "";
}
return (--mapLive[key].upper_bound(timestamp))->second;
}
};