C++ .size()

javier_alvarez's avatar
Published Aug 9, 2025
Contribute to Docs

The .size() method is used to determine the number of elements currently stored in a std::set.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.
    • Beginner Friendly.
      11 hours

Syntax

setName.size();

Parameters:

This method does not take any parameters.

Return value:

Returns the current number of elements in the set as an unsigned integer (size_type).

Example: Calculating the Average of Set Elements

In this example, a set is created, values are inserted, and the average of the elements is calculated using .size() to get the count:

#include <iostream>
#include <set>
int main() {
// Initialize set
std::set<int> numbers;
// Insert values into set
numbers.insert(24);
numbers.insert(26);
numbers.insert(30);
numbers.insert(20);
int sum = 0;
for (int num : numbers) {
sum += num;
}
// Calculate and print average
std::cout << "The average of the integers in the set is: "
<< sum / numbers.size() << "\n";
return 0;
}

The output of this code is:

The average of the integers in the set is: 25

Codebyte Example

This codebyte example creates a grades set of type int, inserts several values, and prints the number of elements:

Code
Output

All contributors

Contribute to Docs

Learn C++ on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.
    • Beginner Friendly.
      11 hours