Chapter 11. Associative Containers
Associative containers support efficient lookup and retrieval by a key.
- Common types:
- Elements ordered by key:
-
- map: key-value pairs
-
- set: key is the value
-
- multimap: map in which a key can appear multiple times
-
- multiset: set in which a key can appear multiple times
-
- Unordered Collections:
-
- unordered_map: map organized by a hash function
-
- unordered_set: set organized by a hash function
-
- Elements ordered by key:
11.2.3. The pair Type
pair<int, pair<int, int>> p = {1, {1, 2}};
pair<int, pair<int, int>> p(1,(1,2));
pair’s member are named as first and second.
p.first = 1;
p.second.first = 1;
p.second.first = 2;
How to return a pair object:
pair<string, int> process(vector<string> &v)
{
// process v
if (!v.empty()) {
return {v.back(), v.back().size()}; // list initialize
} else
return pair<string, int>("empty", 0); // explicitly constructed return value
}
}
If v isn’t empty, we return a pair composed of the last string in v and the size of
that string. Otherwise, we return empty and 0 as a pair.
自定义比较map
class A{
public:
int a_;
A(int a): a_(a){};
};
bool WannaBigger(const A& a, const A& b) {
return a.a_> b.a_;
}
void func() {
// key, value
map<A, int, decltype(WannaBigger)*> map(WannaBigger);
// 我们自定义了变量A,也要同时定义映射关系(comparator),map本身就是一种hash结构,他把key映射到空间上
// 注意定义的map也要有WannaBigger!!!
map.insert({A(1), 1});
map.insert({A(2), 2});
map.insert({A(3), 3});
map.insert({A(4), 4});
for (auto it = map.begin(); it != map.end(); it++) {
cout << it->second << endl; // 4 3 2 1
}
}
int main() {
func();
return 0;
}
operators:
c[k]: return element with key k, if not in c, adds a new element with key k.
c.at(k): checked access to the element with key k; throws an out_of_range exception if k not in c.
c.find(k): returns an iterator to the first element with key k. For the containers with unique key (not multimap or multiset), the result is always zero and one.
c,count(k): return the num of elements with key k. For the containers with unique key (not multimap or multiset), the result is always zero and one.
c.lower_bound(k): returns an iterator to the first element with key not less than k.
c.upper_bound(k): returns an iterator to the first element with key greater than k.
However, as we’ve just seen, using a subscript has an
important side effect: If that key is not already in the map, then subscript inserts an
element with that key!!!
Buckets for unordered containers
The unordered containers are organized as a collection of buckets, each of which
holds zero or more elements. These containers use a hash function to map elements
to buckets
Summary
Ordered containers use a comparison function to order the elements by key. By default, the comparison is the < operator on the keys. Unordered containers use the
key type’s == operator and an object of type hash<key_type> to organize their elements.