Back to Blog

Map vs. Set: Differences and Similarities

Excerpt 1:

A node in a std::map stores a key-value pair. A node in a std::set stores a single value.

A std::map uses a key to uniquely identify each member. A std::set is a collection. Both belong to associative containers. However, a std::map is declared as: map<type1, type2> mymap; And a std::set is declared as: set<type> myset;

A std::set (collection) contains sorted data, and the values in a set must be unique.

A std::map (mapping) is a collection of sorted pairs. Each element in a map consists of two values: a key (the key in a map must be unique), which is used for sorting or searching and whose associated value can be retrieved from the container. For example, in addition to finding data like ar[43] = "overripe", a map allows finding data using ar["banana"] = "overripe". If you want to retrieve element information, you can easily do so by providing the full name (key) of the element.

A std::map is a mapping where keys within the collection must be unique. A std::set can perform various set operations (union, intersection, difference, etc.). While you could implement a set using list or vector, the efficiency would be very low. Sets are typically implemented using balanced trees or hash tables. A mapping represents a one-to-one relationship, and hash tables can also be viewed as a type of mapping. Mappings are commonly used to implement dictionary structures.

Excerpt 2:

The C++ STL has garnered widespread praise and is widely used, not just for providing convenient containers like vector, string, and list, but more importantly, for encapsulating many complex data structure algorithms and a large number of common data structure operations. vector encapsulates arrays, list encapsulates linked lists, and map and set encapsulate binary trees, among other structures. When encapsulating these data structures, the STL provides common operations such as insertion, sorting, deletion, and searching as member functions, aligning with programmers' usage habits. This ensures users feel familiar when using the STL.