Skip to content

Commit 09faf3b

Browse files
[Term Entry] C++ Deque : back() (#7893)
* [Edit] Python: Python CLI arguments * Update command-line-arguments.md * [Term Entry] C++ Deque : back() * Apply suggestion from @avdhoottt * Apply suggestion from @avdhoottt ---------
1 parent 12246f3 commit 09faf3b

File tree

1 file changed

+81
-0
lines changed
  • content/cpp/concepts/deque/terms/back

1 file changed

+81
-0
lines changed
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
---
2+
Title: '.back()'
3+
Description: 'Returns a reference to the last element in the deque.'
4+
Subjects:
5+
- 'Computer Science'
6+
- 'Game Development'
7+
Tags:
8+
- 'Containers'
9+
- 'Data Structures'
10+
- 'Deques'
11+
- 'Methods'
12+
CatalogContent:
13+
- 'learn-c-plus-plus'
14+
- 'paths/computer-science'
15+
---
16+
17+
In C++, the **`.back()`** [method](https://www.codecademy.com/resources/docs/cpp/methods) returns a reference to the last element in a [deque](https://www.codecademy.com/resources/docs/cpp/deque). It allows direct access to that element for reading or modifying without removing it.
18+
19+
> **Note:** Calling `.back()` on an empty deque leads to undefined behavior. Check with [`.empty()`](https://www.codecademy.com/resources/docs/cpp/deque/empty) before using `.back()`.
20+
21+
## Syntax
22+
23+
```pseudo
24+
dequeName.back();
25+
```
26+
27+
**Parameters:**
28+
29+
This method does not take any parameters.
30+
31+
**Return value:**
32+
33+
Returns a reference to the last element of the deque. If the deque is `const`, it returns a `const` reference.
34+
35+
## Example: Accessing and Updating the Last Element
36+
37+
This example retrieves the last number in a deque, updates it, and displays the change:
38+
39+
```cpp
40+
#include <deque>
41+
#include <iostream>
42+
43+
int main() {
44+
std::deque<int> scores = {45, 67, 89};
45+
46+
std::cout << "Last score: " << scores.back() << std::endl;
47+
48+
// Update the last element
49+
scores.back() = 100;
50+
51+
std::cout << "Updated last score: " << scores.back() << std::endl;
52+
return 0;
53+
}
54+
```
55+
56+
This program produces the following output:
57+
58+
```shell
59+
Last score: 89
60+
Updated last score: 100
61+
```
62+
63+
## Codebyte Example: Using `.back()` in a Conditional Check
64+
65+
This example shows how `.back()` can be used to verify or modify the final value in a deque:
66+
67+
```codebyte/cpp
68+
#include <deque>
69+
#include <iostream>
70+
71+
int main() {
72+
std::deque<std::string> tasks = {"plan", "write", "review"};
73+
74+
if (tasks.back() == "review") {
75+
tasks.back() = "submit"; // Update the last task
76+
}
77+
78+
std::cout << "Final task: " << tasks.back() << std::endl;
79+
return 0;
80+
}
81+
```

0 commit comments

Comments
 (0)