- Modern C++:Efficient and Scalable Application Development
- Richard Grimes Marius Bancila
- 309字
- 2021-06-10 18:28:20
Sets and multisets
Sets behave as if they are maps, but the key is the same as the value; for example, the following:
set<string> people{
"Washington","Adams", "Jefferson","Madison","Monroe",
"Adams", "Van Buren","Harrison","Tyler","Polk"};
for (string s : people) cout << s << endl;
This will print out nine people in alphabetical order because there are two items called Adams, and the set class will reject duplicates. As the items are inserted into the set it will be ordered, and in this case the order is determined by the lexicon ordering of comparing two string objects. If you want to allow duplicates, so that ten people will be placed in the container, then you should use multiset instead.
As with a map, you cannot change the key of an item in the container because the key is used to determine the ordering. For a set, the key is the same as the value, so this means that you cannot change the item at all. If the intention is to perform lookups, then it may be better to use a sorted vector instead. A set will have more memory allocation overhead than a vector. Potentially, a lookup on a set container will be quicker than on a vector container if the search is sequential, but if you use a call to binary_search (explained in the Sorting items section, later) it could be faster than the associative container.
The interface to the set class is a restricted version of the map class, so you can insert and emplace items in the container, assign it to values in another container, and you have iterator access (begin and end methods).
Since there is no distinct key, it means that the find method looks for a value, not a key (and similarly with the bounds methods; for example, equal_range). There is no at method, nor an [] operator.