6 Vectors – your arrays on steroids

 

This chapter covers

  • Understanding the role and use of std::vector
  • Learning how to declare and initialize vectors
  • Understanding how to access vector elements
  • Understanding the difference between size and capacity
  • Using various methods to modify and manipulate vectors

Now that you have learned about arrays and how they are used to manage collections of objects, it's time to introduce you to another fundamental data structure in C++ - vectors. While arrays have a fixed size, vectors, which, like std::array, are a type of container in C++, can dynamically change their size during runtime, making them more flexible and convenient for many programming tasks.

In this chapter, you will learn how to define and initialize a vector, how to access its elements, and how to manipulate them using various methods which are part of the std::vector container. We will go over useful methods which are part of the std::vector container, such as methods to insert elements to a vector, modify the vector, manage its size and capacity, and more.

We will also explore the difference between vectors and arrays, and when it's appropriate to use one over the other. By the end of this chapter, you will have a solid understanding of how to use vectors in your C++ programs and the benefits they offer over arrays.

6.1 To the vector go the spoils – introduction to vectors

6.1.1 Using vectors in your code

6.1.2 Accessing and assigning vector elements

6.1.3 Using vector modifiers

6.1.4 Assign from heaven: Assigning values to vectors

6.2 Final coding exercise

6.2.1 Intro and recap for some old and new concepts

6.2.2 How to write this code

6.3 Summary