Skip to content
This repository was archived by the owner on Feb 27, 2026. It is now read-only.

Commit 5001379

Browse files
authored
Merge branch 'main' into add-data-visualization-in-UX
2 parents 9061e8d + 9fc825f commit 5001379

7 files changed

Lines changed: 1080 additions & 0 deletions

File tree

Lines changed: 189 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,189 @@
1+
---
2+
Title: '.at()'
3+
Description: 'Returns a reference to the element at the specified position with bounds checking in std::array containers.'
4+
Subjects:
5+
- 'Computer Science'
6+
- 'Web Development'
7+
Tags:
8+
- 'Arrays'
9+
- 'Functions'
10+
- 'Methods'
11+
CatalogContent:
12+
- 'learn-c-plus-plus'
13+
- 'paths/computer-science'
14+
---
15+
16+
The **`.at()`** [method](https://www.codecademy.com/resources/docs/cpp/methods) in C++ is a member [function](https://www.codecademy.com/resources/docs/cpp/functions) of the `std::array` container that provides safe access to elements by their position index. Unlike the subscript operator (`[]`), the `.at()` method automatically performs bounds checking and throws an `std::out_of_range` [exception](https://www.codecademy.com/resources/docs/cpp/exceptions) if the specified index is invalid. This makes it a safer alternative for element access when you need to ensure that array bounds are not violated.
17+
18+
The `.at()` method is particularly useful in scenarios where data integrity and [error](https://www.codecademy.com/resources/docs/cpp/errors) handling are critical, such as processing user input, parsing data files, or working with indices that might be calculated dynamically. It provides a balance between safety and performance, making code more robust while maintaining reasonable execution speed.
19+
20+
## Syntax
21+
22+
```pseudo
23+
array_name.at(i)
24+
```
25+
26+
**Parameters:**
27+
28+
- `i`: The zero-based index position of the element to access. Must be a non-negative integer value of type `size_type` (typically `std::size_t`). Valid indices range from `0` to `size()-1`. If the index is greater than or equal to the array size, an `std::out_of_range` exception is thrown.
29+
30+
**Return value:**
31+
32+
The `.at()` method returns a reference to the element at the specified position. If the array object is const-qualified, it returns a `const_reference`; otherwise, it returns a `reference` that allows both reading and modifying the element.
33+
34+
**Exception:**
35+
36+
Throws `std::out_of_range` exception if `pos` is greater than or equal to the size of the array.
37+
38+
## Example 1: Basic Element Access
39+
40+
This example demonstrates the fundamental usage of the `.at()` method to safely access elements in a `std::array`:
41+
42+
```cpp
43+
#include <iostream>
44+
#include <array>
45+
46+
int main() {
47+
// Create an array of integers with 5 elements
48+
std::array<int, 5> numbers = {10, 20, 30, 40, 50};
49+
50+
// Access elements using .at() method
51+
std::cout << "Element at index 0: " << numbers.at(0) << std::endl;
52+
std::cout << "Element at index 2: " << numbers.at(2) << std::endl;
53+
std::cout << "Element at index 4: " << numbers.at(4) << std::endl;
54+
55+
// Modify an element using .at() method
56+
numbers.at(1) = 99;
57+
std::cout << "Modified element at index 1: " << numbers.at(1) << std::endl;
58+
59+
return 0;
60+
}
61+
```
62+
63+
The output of this code is:
64+
65+
```shell
66+
Element at index 0: 10
67+
Element at index 2: 30
68+
Element at index 4: 50
69+
Modified element at index 1: 99
70+
```
71+
72+
This example shows how `.at()` can be used for both reading and writing array elements. The method provides direct access to elements at valid indices and allows modification of non-const arrays.
73+
74+
## Example 2: Safe Input Processing
75+
76+
This example demonstrates using `.at()` method in a real-world scenario where user input needs to be validated before accessing array elements:
77+
78+
```cpp
79+
#include <iostream>
80+
#include <array>
81+
#include <stdexcept>
82+
83+
int main() {
84+
// Array storing daily temperatures for a week
85+
std::array<double, 7> weeklyTemps = {22.5, 25.1, 21.8, 24.3, 26.7, 23.9, 20.2};
86+
std::array<std::string, 7> dayNames = {"Monday", "Tuesday", "Wednesday",
87+
"Thursday", "Friday", "Saturday", "Sunday"};
88+
89+
int dayChoice;
90+
std::cout << "Enter day number (1-7) to get temperature: ";
91+
std::cin >> dayChoice;
92+
93+
try {
94+
// Convert 1-based input to 0-based index and use .at() for safe access
95+
int index = dayChoice - 1;
96+
double temperature = weeklyTemps.at(index);
97+
std::string dayName = dayNames.at(index);
98+
99+
std::cout << "Temperature on " << dayName << ": " << temperature << "°C" << std::endl;
100+
}
101+
catch (const std::out_of_range& e) {
102+
std::cout << "Error: Invalid day number. Please enter a number between 1 and 7." << std::endl;
103+
}
104+
105+
return 0;
106+
}
107+
```
108+
109+
The output of this code is (If user enters 3):
110+
111+
```shell
112+
Enter day number (1-7) to get temperature: 3
113+
Temperature on Wednesday: 21.8°C
114+
```
115+
116+
Output (if user enters 10):
117+
118+
```shell
119+
Enter day number (1-7) to get temperature: 10
120+
Error: Invalid day number. Please enter a number between 1 and 7.
121+
```
122+
123+
This example demonstrates how `.at()` method's bounds checking helps create robust applications that handle invalid user input gracefully without crashing.
124+
125+
## Codebyte Example: Grade Management System
126+
127+
This example shows the `.at()` method being used in a practical grade management scenario where safe access to student scores is essential:
128+
129+
```cpp
130+
#include <iostream>
131+
#include <array>
132+
#include <iomanip>
133+
#include <stdexcept>
134+
135+
int main() {
136+
// Array storing test scores for 5 students
137+
std::array<double, 5> testScores = {85.5, 92.3, 78.9, 96.1, 88.7};
138+
std::array<std::string, 5> studentNames = {"Alice", "Bob", "Charlie", "Diana", "Eve"};
139+
140+
// Function to display a specific student's grade
141+
auto displayGrade = [&](int studentId) {
142+
try {
143+
double score = testScores.at(studentId);
144+
std::string name = studentNames.at(studentId);
145+
146+
std::cout << std::fixed << std::setprecision(1);
147+
std::cout << "Student: " << name << ", Score: " << score << "%" << std::endl;
148+
149+
// Determine grade based on score
150+
if (score >= 90) std::cout << "Grade: A" << std::endl;
151+
else if (score >= 80) std::cout << "Grade: B" << std::endl;
152+
else if (score >= 70) std::cout << "Grade: C" << std::endl;
153+
else std::cout << "Grade: F" << std::endl;
154+
}
155+
catch (const std::out_of_range& e) {
156+
std::cout << "Error: Student ID " << studentId << " not found." << std::endl;
157+
}
158+
};
159+
160+
// Display all students
161+
std::cout << "=== Class Grades ===" << std::endl;
162+
for (size_t i = 0; i < testScores.size(); ++i) {
163+
displayGrade(i);
164+
std::cout << std::endl;
165+
}
166+
167+
// Test invalid access
168+
std::cout << "Attempting to access invalid student ID:" << std::endl;
169+
displayGrade(10);
170+
171+
return 0;
172+
}
173+
```
174+
175+
This example illustrates how the `.at()` method enables the creation of robust data management systems where array bounds are automatically validated, preventing potential crashes and providing clear error feedback.
176+
177+
## Frequently Asked Questions
178+
179+
### 1. What is the difference between `.at()` and the subscript operator `[]`?
180+
181+
The `.at()` method performs bounds checking and throws an `std::out_of_range` exception for invalid indices, while the subscript operator `[]` does not check bounds and may result in undefined behavior if an invalid index is used.
182+
183+
### 2. When should I use `.at()` instead of `[]`?
184+
185+
Use `.at()` when you need guaranteed bounds checking, especially when dealing with user input, dynamic indices, or when building robust applications where safety is more important than maximum performance.
186+
187+
### 3. What happens if I try to access an element beyond the array size?
188+
189+
The `.at()` method will throw an `std::out_of_range` exception, which you can catch and handle appropriately in your code.
Lines changed: 167 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,167 @@
1+
---
2+
Title: '.swap()'
3+
Description: 'Exchanges the values of two pointers or container elements, allowing efficient data manipulation without deep copies.'
4+
Subjects:
5+
- 'Computer Science'
6+
- 'Data Science'
7+
Tags:
8+
- 'Functions'
9+
- 'Memory'
10+
- 'Pointers'
11+
CatalogContent:
12+
- 'learn-c-plus-plus'
13+
- 'paths/computer-science'
14+
---
15+
16+
The **`.swap()`** function in C++ is used to exchange the values or contents of two [variables](https://www.codecademy.com/resources/docs/cpp/variables), including [pointers](https://www.codecademy.com/resources/docs/cpp/pointers) and [objects](https://www.codecademy.com/resources/docs/cpp/objects). When used with pointers, `std::swap()` simply exchanges the memory addresses they store, not the values pointed to. It is especially useful for efficiently reassigning ownership of dynamically allocated memory or switching references between data structures.
17+
18+
Swapping pointers is a common practice in algorithms (e.g., linked lists, trees), memory management, and system-level programming. It provides an efficient way to manipulate references without copying or reallocating the underlying data.
19+
20+
## Syntax
21+
22+
```pseudo
23+
std::swap(ptr1, ptr2);
24+
```
25+
26+
**Parameters:**
27+
28+
- `ptr1`, `ptr2`: Two pointer variables (e.g., `int*`, `char*`, `MyClass*`, etc.)
29+
- These must be of the same type.
30+
- After swapping, the memory addresses stored in `ptr1` and `ptr2` are exchanged.
31+
32+
**Return value:**
33+
34+
No return value. The swap is done in-place by modifying the pointer variables.
35+
36+
## Example 1: Swapping Integer Pointers
37+
38+
In this example, `std::swap()` is used to exchange the memory addresses stored in two integer pointers, changing which variables the pointers reference:
39+
40+
```cpp
41+
#include <iostream>
42+
#include <utility> // For std::swap
43+
44+
int main() {
45+
int a = 10, b = 20;
46+
int* ptr1 = &a;
47+
int* ptr2 = &b;
48+
49+
std::cout << "Before swap:\n";
50+
std::cout << "ptr1 points to: " << *ptr1 << "\n";
51+
std::cout << "ptr2 points to: " << *ptr2 << "\n";
52+
53+
std::swap(ptr1, ptr2);
54+
55+
std::cout << "After swap:\n";
56+
std::cout << "ptr1 points to: " << *ptr1 << "\n";
57+
std::cout << "ptr2 points to: " << *ptr2 << "\n";
58+
59+
return 0;
60+
}
61+
```
62+
63+
The output of this code is:
64+
65+
```shell
66+
Before swap:
67+
ptr1 points to: 10
68+
ptr2 points to: 20
69+
After swap:
70+
ptr1 points to: 20
71+
ptr2 points to: 10
72+
```
73+
74+
Here, the memory addresses stored in `ptr1` and `ptr2` were swapped, so the variables they point to were exchanged without moving or modifying the original data.
75+
76+
## Example 2: Swapping Pointers in Dynamic Memory
77+
78+
In this example, `std::swap()` is applied to pointers referencing dynamically allocated memory, enabling efficient exchange of their targets without copying values:
79+
80+
```cpp
81+
#include <iostream>
82+
#include <utility>
83+
84+
int main() {
85+
int* p1 = new int(5);
86+
int* p2 = new int(15);
87+
88+
std::cout << "Before swap: *p1 = " << *p1 << ", *p2 = " << *p2 << "\n";
89+
90+
std::swap(p1, p2);
91+
92+
std::cout << "After swap: *p1 = " << *p1 << ", *p2 = " << *p2 << "\n";
93+
94+
delete p1;
95+
delete p2;
96+
97+
return 0;
98+
}
99+
```
100+
101+
The output of this code is:
102+
103+
```shell
104+
Before swap: *p1 = 5, *p2 = 15
105+
After swap: *p1 = 15, *p2 = 5
106+
```
107+
108+
This shows that the values pointed to by the two heap-allocated pointers are swapped efficiently. Always ensure proper memory cleanup using `delete` or smart pointers.
109+
110+
## Codebyte Example: Swapping Class Pointers
111+
112+
In this example, two pointers to `Student` class instances are swapped using `std::swap()`, transferring ownership of the object references without modifying the objects themselves:
113+
114+
```codebyte/cpp
115+
#include <iostream>
116+
#include <string>
117+
#include <utility>
118+
119+
class Student {
120+
public:
121+
std::string name;
122+
Student(std::string n) : name(n) {}
123+
void display() const {
124+
std::cout << "Student: " << name << std::endl;
125+
}
126+
};
127+
128+
int main() {
129+
Student* s1 = new Student("Alice");
130+
Student* s2 = new Student("Bob");
131+
132+
std::cout << "Before swap:\n";
133+
s1->display();
134+
s2->display();
135+
136+
std::swap(s1, s2);
137+
138+
std::cout << "After swap:\n";
139+
s1->display();
140+
s2->display();
141+
142+
delete s1;
143+
delete s2;
144+
145+
return 0;
146+
}
147+
```
148+
149+
This demonstrates pointer swapping with class objects. The actual student objects are untouched—only the pointers are exchanged.
150+
151+
## Frequently Asked Questions
152+
153+
### 1. Is `.swap()` a member function of pointers?
154+
155+
No, raw pointers do not have a `.swap()` member function. You should use `std::swap()` from the `<utility>` header to swap them.
156+
157+
### 2. What’s the difference between swapping pointers vs. values?
158+
159+
Swapping pointers exchanges memory addresses, not the values pointed to. To swap actual values, dereference the pointers:
160+
161+
```cpp
162+
std::swap(*ptr1, *ptr2);
163+
```
164+
165+
### 3. Can I use `.swap()` with smart pointers?
166+
167+
Yes, `std::swap()` works with `std::unique_ptr`, `std::shared_ptr`, and other smart pointers. These types may also provide their own `.swap()` member methods for more efficient swapping.

0 commit comments

Comments
 (0)