Small Steps V — Making Your Own Types
Reading without copying
Read without copying.
What you will learn
A const reference lets you read the original without copying it, while promising not to change it through that reference.
Try it
Example · example2.cpp
int sum(const Array<int>& numbers)
{
int total = 0;
for (int i = 0; i < numbers.length(); i = i + 1)
total = total + numbers[i];
return total;
}
void small_main()
{
Array<int> numbers = {3, 7, 2, 9, 4};
print("Sum: ", sum(numbers));
}
In const Array<int>& numbers, & marks a reference to the original and const makes it read-only. The output is Sum: 25.
The sum needs no copy of the whole array. Attempting to change it causes a compilation error. The earlier Array<int> parameter is also valid, but copying can be costly for large arrays.
Exercise
Change the earlier find_largest(Array<int> numbers) to use const Array<int>&. The function does not modify the Array.
Exercise starter · exercise2_starter.cpp
int find_largest(Array<int> numbers)
{
int largest = numbers[0];
for (int i = 1; i < numbers.length(); i = i + 1)
if (numbers[i] > largest)
largest = numbers[i];
return largest;
}
void small_main()
{
Array<int> numbers = {4, 12, 3, 9};
print(find_largest(numbers));
}
Hint
Change only the parameter to const Array<int>& numbers; the algorithm can stay the same.
show solution
int find_largest(const Array<int>& numbers)
{
int largest = numbers[0];
for (int i = 1; i < numbers.length(); i = i + 1)
if (numbers[i] > largest)
largest = numbers[i];
return largest;
}
void small_main()
{
Array<int> numbers = {4, 12, 3, 9};
print(find_largest(numbers));
}