Skip to content

[Term Entry] C++ Array Function: .cend() #7194

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 3 commits 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
76 changes: 76 additions & 0 deletions content/cpp/concepts/arrays/terms/cend/cend.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
---
Title: '.cend()'
Description: 'Returns a constant iterator pointing just past the last element of an array container.'
Subjects:
- 'Code Foundations'
- 'Computer Science'
Tags:
- 'Arrays'
- 'Iterators'
CatalogContent:
- 'learn-c-plus-plus'
- 'paths/computer-science'
---

**`.cend()`** is a member function of standard C++ containers (such as [arrays](https://www.codecademy.com/resources/docs/cpp/arrays), [vectors](https://www.codecademy.com/resources/docs/cpp/vectors), and [sets](https://www.codecademy.com/resources/docs/cpp/sets)) that returns a constant iterator pointing just past the last element of the container. The "c" in `.cend()` stands for "const", indicating that the iterator cannot modify the elements it accesses. This function is commonly used for read-only traversal and is typically employed in range checks or `for` loops to define the end boundary of the container.

## Syntax

```pseudo
array.cend();
```

**Parameters:**

This function does not take any parameters.

**Return value:**

Returns a constant iterator pointing just past the last element of the container.

## Example: Using `.cend()` to Access the Last Element

This example prints the last element of the array by using `.cend()` and moving one step backward:

```cpp
#include <iostream>
#include <array>

int main() {
std::array<int, 2> array = {1, 2};

// Get constant iterator just past the last element
auto it = array.cend();

// Move one step back to point to the last element
std::cout << *(std::prev(it)) << "\n"; // Outputs: 2

return 0;
}
```

The output of this program will be:

```shell
2
```

## Codebyte Example: Using `.cend()` to Print an Array

The following code creates an array and uses `.cbegin()` and `.cend()` to print all of its elements:

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

int main() {
std::array<int, 4> array = {1, 2, 3, 4};

// Prints all elements in the array using const iterators
for (auto i = array.cbegin(); i != array.cend(); ++i) {
std::cout << *i << " ";
}

return 0;
}
```