C++ .size()
Published Aug 9, 2025
Contribute to Docs
The .size() method is used to determine the number of elements currently stored in a std::set.
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 setstd::set<int> numbers;// Insert values into setnumbers.insert(24);numbers.insert(26);numbers.insert(30);numbers.insert(20);int sum = 0;for (int num : numbers) {sum += num;}// Calculate and print averagestd::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:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve 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