tags:

views:

253

answers:

3

Hi

I find that both set and map are implemented as a tree. set is a binary search tree, map is a self-balancing binary search tree, such as red-black tree? I am confused about the difference about the implementation. The difference I can image are as follow

1) element in set has only one value(key), element in map has two values. 2) set is used to store and fetch elements by itself. map is used to store and fetch elements via key.

What else are important?

Thanks!

+4  A: 

Maps and sets have almost identical behavior and it's common for the implementation to use the exact same underlying technique.

The only important difference is map doesn't use the whole value_type to compare, just the key part of it.

Roger Pate
+1  A: 

Usually you'll know right away which you need: if you just have a bool for the "value" argument to the map, you probably want a set instead.

Set is a discrete mathematics concept that, in my experience, pops up again and again in programming. The stl set class is a relatively efficient way to keep track of sets where the most common opertions are insert/remove/find.

Maps are used where objects have a unique identity that is small compared to their entire set of attributes. For example, a web page can be defined as a URL and a byte stream of contents. You could put that byte stream in a set, but the binary search process would be extremely slow (since the contents are much bigger than the URL) and you wouldn't be able to look up a web page if its contents change. The URL is the identity of the web page, so it is the key of the map.

David Gladfelter
Unless true/false/not-present are all distinct states. :) A map applies when part of the value can change (the std::map::mapped_type, specifically) without changing the identity of the value, rather than just being an "efficient set".
Roger Pate
A: 

A map is usually implemented as a set< std::pair<> >.

The set is used when you want an ordered list to quickly search for an item, basically, while a map is used when you want to retrieve a value given its key.

In both cases, the key (for map) or value (for set) must be unique. If you want to store multiple values that are the same, you would use multimap or multiset.

Joel