How to Find the Size of a Set in Bytes in C++?
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::set::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++
#include <iostream>
#include <set>
using namespace std;
int main()
{
set< int > s = { 1, 2, 3, 4 };
int setSize = s.size();
int elementSize = sizeof (*s.begin());
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)
Share your thoughts in the comments
Please Login to comment...