Understanding C++ Vectors, and Strings
Introduction
Welcome to this course!
Before we dive into the essentials of C++ for interview preparation, let's begin with a review of some fundamental concepts within C++. In particular, we'll discuss C++ containers, vectors and strings. These tools are important for grouping multiple elements such as numbers or letters under a single entity.
Understanding C++'s Containers
A fundamental distinction of C++ containers is that they are mutable, meaning we can change their contents after their creation. Let's review how to create and modify vectors:
Diving Into Vectors
Vectors are dynamic arrays provided by the C++ Standard Template Library. They not only help us organize data such that each element holds a specific position, or index, but also provide several built-in functions for managing the stored data effectively. These functions include push_back(), insert(), erase(), and find(), and they allow us much flexibility when handling vectors.
push_back() is a function that allows you to add a new element to the end of the vector. This increases the size of the vector by one.
insert() provides a way to add an element at a specific position in a vector. The position is indicated by an iterator. This function shifts the position of all elements after the specified position by one.
The find() function comes from the <algorithm> library of STL and is used to find the position of a specific element within a vector. It takes a range provided by begin() and end() to look for the element.
erase() is a function that removes a specific element or a range of elements from the vector. This is done by specifying the position or range using iterators.
The begin() function returns an iterator pointing to the first element of the vector while end() returns an iterator pointing to the position past the last element of the vector.
The example below illustrates the use of these functions.
In this code, the push_back() function adds "date" to the end of the fruits vector. The insert() function adds "bilberry" at the second position of the vector. The find() and erase() functions remove "banana" from the vector. We also use the indexing approach to access the first and last elements of the vector.
