CS 70

Before You Start

We know that the C++ standard library provides a fill function, which can set every item in a collection to a given value. Let's imagine implementing it ourselves!

Fill in the body of the function. (Hint: It'll be a for loop.)

void fill(vector<int>::iterator startingPoint, vector<int>::iterator pastTheEnd, int val) {
}

Here's how I would implement it…

void fill(vector<int>::iterator startingPoint, vector<int>::iterator pastTheEnd, int val) {
    for (vector<int>::iterator iter = startingPoint; iter != pastTheEnd; ++iter) {
        *iter = val;
    }
}
  • Duck speaking

    I used auto, is that okay?

  • LHS Cow speaking

    Yes, that's fine. In fact, it's a good idea to use auto in this kind of scenario, because it makes your code more robust to changes in the type of the iterator. For example, if you later decide to change the type of the vector to list<int>, you won't need to change the type of the iterator in the for loop.

  • Goat speaking

    Meh. I think it's tedious that you had to write it out anywhere. It'd be cooler if the compiler could just figure it out for you everywhere.

  • Bjarne speaking

    Well…

  • LHS Cow speaking

    That's what today's lesson is about! At least kinda…

(When logged in, completion status appears here.)