Common Array Operations
Explore how to perform fundamental array operations such as access, insertion, update, and deletion in C++. Understand the performance costs of each operation and learn best practices for efficient array manipulation. This lesson equips you with practical skills to manage arrays effectively in C++ programming.
We'll cover the following...
Before writing any algorithm, we need to know what we can actually do with an array. Arrays support a small, fixed set of operations. Each one is simple to learn, but together they cover almost everything we will ever need: reading values, adding new ones, changing them, removing old ones, and scanning through the entire collection.
In this lesson, we will go through each operation one by one.
Access (Read an element)
The most basic thing you can do with an array is read a value stored in it. This is called accessing an element. Think of it like looking up a specific game on our scorecard.
Syntax:
To access an element, we write the array name followed by the index of the element we want to access in square brackets:
array[index]
Example: Consider the following scores array: {88, 95, 70, 82, 91}. If we want to access the score of game 3, we will use scores[2], which will give us 70.
C++ implementation:
The following code shows how to access the score at index 2 from the scores array:
With std::vector, the syntax is identical:
Note: Accessing an index that does not exist using [] is undefined behavior in C++. The program may crash, produce garbage output, or appear to work. For safer access with bounds checking, use the .at() member function, which throws an std::out_of_range exception if the index is invalid.
Insertion (Add an element)
Insertion means adding a new element to the array. When you insert an element, the array grows by one. However, not all insertions are equal. The cost of insertion depends on where the new element goes in the array.
Insert at the end
Adding an element to the end of the array is the simplest kind of insertion. Because the new element goes into the next empty slot at the end, nothing else in the array needs to move. Think of it like adding a new row to the end of our scorecard and writing the score in.
Syntax:
To append an element to the end of a std::vector, we use:
vector.push_back(value)
Example: Consider a scores vector {88, 95, 70, 82}. A fifth game has been played, and ...