The first element is
a[0]
, the second is
a[1]
, and so on, and the last (10th) element is
a[9]
.
Note that the first element is actually position
zero, not position one.
So if you wanted to print all of the elements, you could use a
for
loop:
1 2
|
for (int i = 0; i < 10; ++i)
std::cout << a[i] << ' '; // Prints all of the elements, separated by spaces
|
You can't really "delete" an element per se, but you can shift all of the elements after it down a spot by assigning every element after that to the previous array position.
That is, if you wanted to "delete" the 5th element (
a[4]
), then you would assign the value of
a[5]
to
a[4]
,
a[6]
to
a[5]
, and so on.
This leaves the last element,
a[9]
, as a sort of "open spot", though it's still part of the array and you can still access/modify it just like any other array element.
So if you want to completely forget about that last element, you can keep track of a
size variable and update it accordingly, and have the rest of your program use that variable to judge where the end of the array is:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
int array[10] = {1,2,3,4,5,6,7,8,9,10};
int size = 10; // Size of the array
// Print the elements
for (int i = 0; i < size; ++i)
std::cout << array[i] << ' ';
std::cout << '\n';
// Delete the 5th element (a[4])
for (int i = 5; i < size; ++i)
array[i-1] = array[i]; // Move the 6th-10th elements down one
--size; // Update size accordingly
// Print elements again
for (int i = 0; i < size; ++i)
std::cout << array[i] << ' '; // This time 'size' is 9, so the last element won't be printed
|