Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a "set" in C++? When are they useful?

I'm having a hard time conceptualizing c++ sets, actually sets in general.

What are they? How are they useful?

like image 294
Monte Hurd Avatar asked Sep 07 '09 22:09

Monte Hurd


People also ask

What is the use of set in C?

Sets in C++ Sets are associative containers that store unique elements. A stored element must be unique because it is identified with the value itself. Once the elements are inserted in the set, they cannot be modified; however, they can be inserted or removed from the container.

What is a set useful for?

The purpose of sets is to house a collection of related objects. They are important everywhere in mathematics because every field of mathematics uses or refers to sets in some way. They are important for building more complex mathematical structure.

Why are sets and maps useful?

Sets are used to get information of an object by providing all the information, usually used to check if the data exists. A map is used to get the information of an object by using a key (single data).

When we should use set in C++?

As mentioned above, sets in C++ are the type of STL containers that are used for storing elements in a sorted way. The operations allowed to be performed on sets are insertion and deletion. The elements are internally sorted according to a strict weak ordering in a set type container.


1 Answers

Don't feel bad if you have trouble understanding sets in general. Most of a degree in mathematics is spent coming to terms with set theory:

http://en.wikipedia.org/wiki/Set_theory

Think of a set as a collection of unique, unordered objects. In many ways it looks like a list:

{ 1, 2, 3, 4 }

but order is unimportant:

{ 4, 3, 2, 1} = { 1, 2, 3, 4}

and repetitions are ignored:

{ 1, 1, 2, 3, 4 } = { 1, 2, 3, 4}

A C++ set is an implementation of this mathematical object, with the odd feature that is is sorted internally. But this is just a detail of implementation, and is not relevant to understanding the data structure. The sorting is just for speed.

like image 124
David Crawshaw Avatar answered Sep 28 '22 01:09

David Crawshaw