Chapter 15 - Worked Exercises 2

Exercise 1 - Vectors

Part 1

  1. Internally, how are the elements of a vector stored or represented? Are they contiguously in memory?

  2. What operations are quick for vectors?

  3. What operations are relatively slow for vectors?

Part 2

Given the following vector declaration:

std::vector<int> numbers = {1, 2, 3, 5, 7, 11, 13};

Enumerate through the vector, and print each element:

  • using a for-loop with indexing

  • using a range-based loop

  • using iterators

Part 3

Accessors

  1. Do vectors support random access (indexing)?

  2. How can you access the value of a vector at index 3?

Capacity

  1. How do you check if a vector is empty?

  2. How do you get the capacity and size of a vector?

  3. What is the difference between the capacity of a vector and its size?

  4. Can the capacity of a vector ever be smaller than its size?

Modifiers

  1. Show an example of inserting the value 100 at index 3 of a vector.

  2. Show an example of inserting multiple elements from one vector into another.

  3. Show an example of removing the value at index 5 of a vector.

  4. Show an example of removing the values from index 2 to index 4 (non inclusive of 4) from a vector.

  5. Show an example of removing all elements from a vector.

Last updated

Was this helpful?