Skip to content

[Term Entry] C++ Sets: size() #7210

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 80 additions & 0 deletions content/cpp/concepts/sets/terms/size.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
---
Title: '.size()'
Description: 'Returns the amount of elements in the set.'
Subjects:
- 'Computer Science'
- 'Game Development'
Tags:
- 'Data Types'
- 'Sets'
CatalogContent:
- 'learn-c-plus-plus'
- 'paths/computer-science'
---

The **`.size()`** method is used to determine the amount of elements that are currently stored in a set.

## Syntax

```pseudo
setName.size();
```

## Example

## Obtaining the median of the numbers in a set

```cpp
#include <iostream>
#include <set>

int main() {
// Initiate 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;
}

// Print amount of elements in set "numbers"
std::cout << "the median of the integers in the set is: " << sum/numbers.size() << "\n";

}

```

### prints:
```shell
the median of the integers in the set is: 25
```

## Codebyte Example

The following codebyte example creates a `grades` set of type `int` and inserts several values before being printed:

```codebyte/cpp
#include <iostream>
#include <set>

int main() {
// Initiate set
std::set<int> numbers;

// Insert values into set
numbers.insert(90);
numbers.insert(34);
numbers.insert(2);
numbers.insert(101);

// Print amount of elements in set "numbers"
std::cout << "The set contains " << numbers.size() << " elements.\n";

}
```