954,498 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

STL set vs. map

What's the difference between a set and a map? (As described below on cppreference)

Set:
The C++ Set is an associative container that contains a sorted set of unique objects.

Map:
C++ Maps are sorted associative containers that contain unique key/value pairs.

I'm having trouble finding the distinction.

winbatch
Posting Pro in Training
466 posts since Feb 2005
Reputation Points: 68
Solved Threads: 18
 

In a set, the value is the key. In a map, the key and value are distinct.

Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 

So is a set like any other list/vector except that it's sorted?

winbatch
Posting Pro in Training
466 posts since Feb 2005
Reputation Points: 68
Solved Threads: 18
 

>So is a set like any other list/vector except that it's sorted?
Sure, you can think of it like that for the time being. :)

Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 

OK. By the way, is there some sort of parent class that all STL containers descend from? Let's say I have my own container class and in it's constructor I have a flag that says I want my container to be sorted or non sorted. If it's sorted, I use set, if it's not sorted, I use vector. (As an example). If so, I would have a pointer to this parent class, and then in the constructor, I would set the pointer = to the descendent class. Does this make sense?

winbatch
Posting Pro in Training
466 posts since Feb 2005
Reputation Points: 68
Solved Threads: 18
 

>By the way, is there some sort of parent class that all STL containers descend from?
No. In fact, all of the standard containers are concrete classes and can't be safely used as base classes because they lack a virtual destructor.

>Does this make sense?
Sorted and not sorted are only minor details. For example, a set doesn't support random access iterators while a vector does. So your container's public interface would change drastically because non-sorted is a sequence container and sorted is an associative container. If you want a sorted vector then the standard sort algorithm can be used periodically, or you can create your own sorted sequence class that contains a vector and supports the operations that you need for it.

Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You