How to Find the Size of a Set in Bytes in C++? (original) (raw)

Last Updated : 22 Feb, 2024

In C++, sets are associative containers that only store unique elements. The elements inside the set are sorted in a specific order. In this article, we will learn how we can find the size of a set in bytes in C++.

**Example

**Input:
S = {1,2,3,4}
**Output: Size of the set in bytes is : 16

Find the Size of a Set in Bytes in C++

We can find the size (number of elements) of a set using the std:📐:size() method easily, however, C++ doesn't have any method that can find the size of a set in bytes. To find the size of a set in bytes, we can multiply the number of elements by the size of each element. We can find the size of each element using sizeof() operator.

C++ Program to Find the Size of a Set in Bytes

C++ `

// C++ Program to Find the Size of a Set in Bytes #include #include using namespace std;

int main() { // Initialize a set with some elements set s = { 1, 2, 3, 4 };

// Calculate the size of the set
int setSize = s.size();
// Calculate the size of any individual element in the
// set by dereferencing the iterator
int elementSize = sizeof(*s.begin());
// Calculate the size of the set in bytes
int size = setSize * elementSize;

cout << "Size of the set in bytes is : " << size
     << endl;

return 0;

}

`

Output

Size of the set in bytes is : 16

**Time Complexity: O(1)
**Auxiliary Space: O(1)