C++ - map and set (multimap and multiset)

Table of contents

1. Associative container

2. Key-value pairs

3. Associative container of tree structure

3.1 set

3.1.1 Introduction to set

3.1.2 Use of set

3.2 multiset

3.2.1 Introduction to multiset

3.2.2 The use of multiset

3.3 map

3.3.1 Introduction to map

3.3.2 Use of map

3.4 multimap

3.4.1 Introduction to multimap

3.4.2 Use of multimap

4. Exercises


1. Associative container

Sequential containers: vector, list, deque, forward_list (C++11), etc., because the bottom layer is a linear sequence data structure, which stores the elements themselves .
So what is an associative container? How is it different from a serial container?
Associative containers are also used to store data. Unlike sequential containers, they store <key, value> structures
Key-value pairs , which are more efficient than sequential containers for data retrieval .

2. Key-value pairs

It is used to represent a structure with one-to-one correspondence . Generally, this structure only contains two member variables key and value , and key represents
Table key value, value represents the information corresponding to the key .
For example: English-Chinese dictionary, English is the key, and the corresponding Chinese is the value

 The type of key is the type of the first template, and the type of value is the type of the second template

The pair design in stl30 is as follows:

template <class T1, class T2>
struct pair {
  typedef T1 first_type;
  typedef T2 second_type;

  T1 first;
  T2 second;
  pair() : first(T1()), second(T2()) {}
  pair(const T1& a, const T2& b) : first(a), second(b) {}

#ifdef __STL_MEMBER_TEMPLATES
  template <class U1, class U2>
  pair(const pair<U1, U2>& p) : first(p.first), second(p.second) {}
#endif
};

3. Associative container of tree structure

Associative containers of tree structure: map, set, multimap, multiset.

What these four containers have in common : use a balanced search tree (that is, a red-black tree ) as its underlying result, and the elements in the container are an ordered sequence.

3.1 set

3.1.1 Introduction to set

set document

1. set is a container that stores elements in a certain order
2. In the set, the value of the element also identifies it (the value is the key, the type is T), and each value must be unique.
The elements of a set cannot be modified in the container (elements are always const), but they can be inserted or removed from the container.
3. Internally, the elements in a set are always sorted according to the specific strict weak ordering criteria indicated by its internal comparison object (type comparison)
Sort.
4. The set container is usually slower than the unordered_set container to access a single element by key, but they allow
Subsets are iterated directly.
5. Set is implemented with a binary search tree (red-black tree) at the bottom layer.
Notice:

1. Different from map/multimap, the real key-value pair <key, value> is stored in map/multimap, and only the
value, but the key-value pair consisting of <value, value> is actually stored at the bottom layer.
2. When inserting elements in the set, you only need to insert the value, and there is no need to construct a key-value pair.
3. The elements in the set cannot be repeated (so you can use set for deduplication).
4. Use the set iterator to traverse the elements in the set to get an ordered sequence
5. The elements in the set are compared by default by less than
6. To find an element in the set, the time complexity is: log(n)
7. The elements in the set are not allowed to be modified
8. The bottom layer in the set is implemented using a binary search tree (red-black tree)

3.1.2 Use of set

  1. set's template parameter list

T: The type of elements stored in the set, and the key-value pairs of <value, value> are actually stored at the bottom layer.
Compare (functor): The elements in the set are compared by default by less than
Alloc: The management method of the element space in the set, using the space configurator provided by STL to manage

      2. Example of using set (view the function of the document)

  • structure

  • iterator

  •  modify operation

3.2 multiset

3.2.1 Introduction to multiset

1. A multiset is a container that stores elements in a specific order, where elements can be repeated .
2. In the multiset, the value of the element will also recognize it (because the multiset itself stores the composition of <value, value>
The key-value pair, so the value itself is the key, the key is the value, and the type is T). The value of the multiset element cannot be in the container
(since elements are always const), but can be inserted or deleted from the container .
3. Internally, elements in a multiset are always ordered according to a specific strict weak ordering criterion dictated by its internal comparison rules (type comparisons)
Sort.
4. The access speed of a multiset container to a single element by key is usually slower than that of an unordered_multiset container, but when using iterative
When the generator is traversed, an ordered sequence will be obtained.
5. The underlying structure of the multiset is a binary search tree (red-black tree).

Notice:

1. In the bottom layer of the multiset, the key-value pairs of <value, value> are stored
2. Only need to insert in the insertion interface of mtltiset
3. The difference with set is that the elements in multiset can be repeated, and the value in set is unique
4. Use an iterator to traverse the elements in the multiset to get an ordered sequence
5. Elements in multiset cannot be modified
6. Find an element in the multiset, the time complexity is log(N)
7. The role of multiset: elements can be sorted

3.2.2 The use of multiset

  • multiset.count (number of statistics)  

  •  multiset.find(val) - Returns an iterator over the first val in the inorder

 

  •  multiset.erase(val) - delete all vals

3.3 map

3.3.1 Introduction to map

map document

1. Map is an associative container, which stores elements composed of key and value in a specific order (compared by key)
prime .
2. In the map, the key value key is usually used to sort and uniquely identify elements, and the value value stores the value associated with this key value key
content. The type of the key value key and the value value may be different, and inside the map, the key and value pass the member type
The value_type is bound together, and its alias name is pair:
typedef pair<const key, T> value_type;
3. Internally, the elements in the map are always sorted according to the key value key.
4. The speed of accessing a single element by key value in map is usually slower than unordered_map container, but map allows
Iterate directly over the elements (that is, when iterating over the elements in the map, you can get an ordered sequence).
5. The map supports subscript accessors , that is, put the key in [], and you can find the value corresponding to the key.
6. Maps are usually implemented as binary search trees (more precisely: balanced binary search trees (red-black trees)).

3.3.2 Use of map

  1. Map template parameter description

     2. The use of map

 The operation is almost the same as that of set, you can read the documentation to learn by yourself, focus on operator[ ]

access element:

If k matches the key of an element in the container , the function returns a reference to its mapped value

If k does not match the key of any element in the container , the function inserts a new element with that key and returns a reference to its mapped value . Note that this always increases the container size by 1, even if no mapped value is assigned to the element (the element is constructed using its default constructor ).

Note: When accessing elements, there is an at() (this function is not commonly used) function similar to operator[], all through
key finds the value corresponding to the key and then returns its reference, the difference is: when the key does not exist, operator[] uses the default
Value and key construct a key-value pair and then insert it, return the default value, and the at() function directly throws an exception .

Summarize:

  • map::operator[ ]

1. There is this key in the map, and a reference to the value is returned. (find, modify value)

2. If there is no such key in the map, a pair(key, V()) will be inserted and a reference to the value will be returned. (insert + modify)

  •  map::insert

1. The key is already in the map, return pair(key_iterator, false)

2. The key is not in the map, return pair(new_key_iterator, true)

3.4 multimap

3.4.1 Introduction to multimap

1. Multimaps are associative containers that store key-value pairs mapped from key and value in a specific order <key,
value>, where the key between multiple key-value pairs can be repeated .
2. In a multimap, the elements are usually sorted and uniquely identified according to the key, and the mapped value stores the content associated with the key.
Allow. The types of key and value may be different, and they are combined through the member type value_type inside the multimap,
value_type is a key-value pair that combines key and value:
typedef pair<const Key, T> value_type;
3. Internally, the elements in the multimap are always sorted according to the specific strict weak ordering criteria specified by their internal comparison objects.
key sorted.
4. The speed of multimap accessing a single element by key is usually slower than unordered_multimap container, but using iteration
The operator directly traverses the elements in the multimap to obtain an ordered sequence of keys.
5. Multimap is implemented with a binary search tree (red-black tree) at the bottom layer.
Note: The only difference between multimap and map is that the key in map is unique, while the key in multimap can be
repeated .

3.4.2 Use of multimap

The interface in multimap can refer to map, and the functions are similar.
Notice:
1. The key in the multimap can be repeated.
2. By default, the elements in the multimap will compare the key as less than
3. There is no overloaded operator[] operation in multimap
4. When used, it is the same as the header file included in map

4. Exercises

Finally, post 2 more exercises for map and set. You can try to write, theory + practice, and you can really understand it if you understand it yourself!

Top K frequent words https://leetcode.cn/problems/top-k-frequent-words/description/

class Solution {
public:
    vector<string> topKFrequent(vector<string>& words, int k) {
        map<string,int>Countmap;
        //map[]插入+修改实现统计
        for(auto& str:words)
        {
            Countmap[str]++;
        }
        //比较次数,我们把次数作为Key,降序排
        multimap<int,string,greater<int>>sortmap;
        for(auto& kv:Countmap)
        {
            sortmap.insert(make_pair(kv.second,kv.first));
        }
        vector<string>v;
        multimap<int,string,greater<int>>::iterator it=sortmap.begin();
        while(k--)
        {
            v.push_back(it->second);
            ++it;
        }
        return v;
    }
};
class Solution {
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        //找交集(有序):小的往后走,相等找到存入并同时走
        set<int>s1(nums1.begin(),nums1.end());
        set<int>s2(nums2.begin(),nums2.end());

        auto it1=s1.begin();
        auto it2=s2.begin();
        vector<int>v;
        while(it1!=s1.end()&&it2!=s2.end())
        {
            if(*it1<*it2)
            {
                ++it1;
            }
            else if(*it2<*it1)
            {
                ++it2;
            }
            else
            {
                v.push_back(*it1);
                ++it1;
                ++it2;
            }
        }
        return v;
    }
};

Guess you like

Origin blog.csdn.net/bang___bang_/article/details/131768362