Home » Array of sets in C++

Array of sets in C++

by Online Tutorials Library

Array of sets in C++

An array is defined as the collection of data items stored in a contiguous manner. An array stores different variables of the same type. It becomes easier to access the variables as they are stored at continuous locations.

For example

Array of sets in C++

This is an array that contains six elements. Let’s say the array name is arr[]. Now, if we want to access the elements, they can access the indices 0 to n-1. Here, n is the size of the array.

Arr[0] = 10

Arr[1] = 20

Arr[2] = 30

Arr[3] = 40

Arr[4] = 50

Arr[5] = 60

Sets

A set is an associative container in which the elements are unique. Unlike an array, the value entered in a set cannot be modified after adding it. However, if we want to update the value in the set, we can remove it first and then enter the modified value.

Syntax

Example

set<int> s —– A set of integer values

set<char> c —- A set of character values

Array of sets

When we say an array of sets, it is a two-dimensional array with a fixed number of rows. Each row can have variable lengths.

In an array of sets, each array index stores a set. The set is accessible via iterators.

Array of sets in C++

Syntax

Example

set<int> s[3] —-> A array of set of int type with size 3

Insertion operation in the array of sets

Insertion will happen with the insert() function as each row is a set here. So, we insert using an array of sets using –

set_variable[row_number].insert(element)

Example

s[0].insert(10) —-> Inserts 10 in row 1

s[1].insert(20) —-> Inserts 20 in row 2

Code

Output

Row 1 = Elements at index 0: 10 20 30 40   Row 2 = Elements at index 1: 50 60 70 80   Row 3 = Elements at index 2: 90 100 110 120   

Deletion operation in an array of sets

When we say deletion of an element here, we are removing the element from the set. The function to remove an element from the set is erase().

Code

In this example, we have removed one element from set 3 and one element from set 2. Remember, the set index is i-1 as the array index starts at 0.

Output

Before removal elements are:  Elements at index 0: 10 20 30 40   Elements at index 1: 50 60 70 80   Elements at index 2: 90 100 110 120     After removal elements are:  Elements at index 0: 10 20 30 40   Elements at index 1: 60 70 80   Elements at index 2: 90 110 120   

Traversal operation in an array of sets

When we traverse an array of sets, we iterate through each set and print all the elements in that set. Iterators are used to traverse the set elements.

Code

In the below example, we create an array of sets having two rows. Row one has three elements in the set, and row 2 has two elements in the set.

To traverse an array of sets, we run an outer loop for the rows. In the inner loop, we use iterators to print each set.

Output

Elements at index 0: 10 15 35   Elements at index 1: 20 30   

You may also like