Identifying Operations
As we've seen, sometimes it's useful to think about all the operations that occur in a piece of code. For example, if we say
double x = 3 * 4 + 5.0;
there are four operations:
- Multiplication:
operator*(int,int)
- Type conversion:
int
→double
- Addition:
operator+(double,double)
- Copy initialization: using
double
's copy constructor to initializex
Let's do some more operation spotting…
Loop #1
Suppose we have an array,
double values[MAX_SIZE];
and we want to think carefully about everything that happens in the loop
double* past_end = values+MAX_SIZE;
for (double* p = value; p != past_end; ++p) {
std::cout << *p << "\n";
}
In the for
loop itself, we can see
- Copy initialization of a
double*
(forpast_end
andp
) !=
operator on twodouble*
s++
operator to update a variable holding adouble*
<<
operator on anostream
and adouble
value*
operator on adouble*
<<
operator on anostream
and"\n"
Just before the for
loop, we figure out the past-the-end point, so we have
+
operator on adouble*
and aptrdiff_t
(like asize_t
but signed)
But we'll focus on the for
-loop operations.
Hay! Why did you list
<<
twice?Because it's actually two different functions that happen to have the same name. One is the output operator for doubles, and the other is an output operator that takes a C-style string.
Loop #2
Suppose we have the array
double values[MAX_SIZE];
and we want to consider the performance of the loop
for (size_t i = 0; i != MAX_SIZE; ++i) {
std::cout << values[i] << "\n";
}
We can see
- Copy-initialization of a
size_t
(fori
) !=
operator on twosize_t
values++
operator to update a variable holding asize_t
<<
operator on anostream
and adouble
value[]
operator on an array ofdouble
s<<
operator on anostream
and"\n"
I converted
values[i]
into*(values+i)
and had two operations for that,*
and+
on pointers. Is that okay?Yes, that's totally fine. It's nice that you remembered that identity, but we don't need to break things down that much right now.
Something to notice here is that the operator[]
to go to the i
th element of a data structure is a more advanced operator than the ones we used in our previous example. Although arrays can support operator[]
efficiently, not all data structures can.
Like linked lists—they can't.
Exactly.
But we're using arrays, so it's fine.
True. For now. We'll come back to these ideas later.
(When logged in, completion status appears here.)