J Moss
J Moss

Reputation: 205

Why is const_iterator used instead of just iterator in this C++ question?

I have a C++ exam question which doesn't make sense to me.

Question:

Using the following library algorithms:

  • find(b, e, v) searches the range [b, e) and returns an iterator pointing at the first occurrence of v, if there is one, or e if there is not,

1. Write a function that takes a list of doubles and returns the number of zeroes in the list. (15 marks)

Answer:

int count_zeroes(const list<double> &l) {
    return count(l.cbegin(), l.cend(), 0);
}

My Question:

I got a similar answer but without the constant reference and I used pass by value instead.

Upvotes: 0

Views: 129

Answers (2)

Rich
Rich

Reputation: 4962

Why is cbegin()/cend() used here instead of just begin()/end() ?

NathanOliver has corrected me on this. It appears that there's no particular reason to use cbegin and cend in this case because the const data structure will return const iterators. It seems using cbegin, cend and begin,end will yield the same results.

Why does the answer include a pass by reference to "&1" (is this specified in the question, perhaps) ?

Passing potentially large data structures by reference is standard practice and efficient compared with passing by value and if you're not going to alter them then passing by const reference is the correct thing to do.

why was 'list' made as a constant variable?

Because it isn't going to be altered inside the method. Using const to denote that something isn't allowed to be changed allows the compiler to apply optimisations it wouldn't be able to apply otherwise.

Upvotes: 0

H S
H S

Reputation: 1221

Why does the answer include a pass by reference to &1 (is this specified in the question, perhaps)?

To avoid creating unnecessary copy of entire list. Remember Objective is to only 'read' contents of list and count zeroes. This helps us in answering another question:

Why was list made as a constant variable

Since we're only supposed to 'read' contents of list and passing by reference implies any change to list will be reflected back in original list. It is a good practice to pass such variables as const to prevent un-intentional changes.

Why is cbegin()/cend() used here instead of just begin()/end()

Just found out, @NathanOliver is right. For completeness, pasting his comment here: begin is overloaded for const objects to return a const_iterator so there is no need to actually use cbegin since l is const.

Upvotes: 2

Related Questions