std::set and std::map

Hi,
I have gone through the description available for std:set and std::map.
I am not understand what are the purpose of two associative containers in STL?

The only difference is unlike in set, map has the separate key value associate with the mapped value?
Are any other differences?

Could anyone Please give me a simple example where we need to use std::set and std::map?

akash16 wrote:
The only difference is unlike in set, map has the separate key value associate with the mapped value?

Yes, that's the main difference. Note that with a set you are not allowed to modify the elements because doing so could mess up the ordering. With a map you cannot modify the keys for the same reason, but you can modify the mapped values all you want.
Yes, Peter agreed with your point.
Because in SET key-value and mapped-value are same not separate like MAP,
Thats why not allowed to modify elements in SET.
I got below simple example for STD::SET and STD::MAP:

Choosing one over the other depends mainly on what the task at hand is.
If you want to build a dictionary of all the words that appear in a text, you could use a std::set<std::string>,
but if you also want to count how many times each word appeared (i.e. associate a value to the key) then you would need an std::map<std::string,int>.

If you don't need to associate that count, it does not make sense to have the int that is unnecessary.
If it helps, you can think of a map as being a little bit like a vector, but with more flexibility in what key you associate your data with.

In a vector, the data is keyed by consecutive integer values, starting with 0 - myVec[0], myVec[1], myVec[2], etc.

In a map, you can choose the type of key, e.g. myMap["cat"], myMap["dog"], myMap["ocelot"].
Last edited on
Underline data structure:
set/map - red-black trees(self-balancing BST)
unordered_set/unordered_map - Hash Tables.
multiset/multimap - self-balancing BST
unordered_multiset/unordered_multimap - same as that of unordered_map i.e. Hash Table
but for duplicate keys another count value is maintained with each key- value pair.

The standard doesn't mandate much so if you can come up with other data structures that fit both functional and complexity requirements of the C++ standard then all is fine.
For example the implementation shipped with VisualStudio is based on a red-black tree.
Topic archived. No new replies allowed.