In this tutorial, we'll learn about different types of containers in C++. In particular, we will learn about vectors, maps and pairs in C++.
Vectors
Earlier, you learnt about C++ Arrays. Vectors are like arrays, but they are more flexible. In particular, you might remember that it is not possible to change the size of a C++ array after it is declared. Vectors provide us the flexibility of inserting and deleting elements even after they are declared.
Declaring a Vector
Suppose you are taking a survey of 100 people and you have to store their age. To solve this problem in C++, you can create a vector of integers with 100 elements. For example:
type=codeblock|id=cpp_vector|autocreate=cpp#include <iostream>#include <vector>using namespace std;int main() {vector <int> age (100); // vector "age" with 100 intsreturn 0;}
Notice that we need to include the vector library first, otherwise we get an error. Also, we specify the data type of the vector elements in angle brackets, like so: <int>.
Here is another way to declare and initialize a vector:
type=codeblock|id=cpp_vector_2|autocreate=cpp// Empty vector of with elements of type "string"vector <string> names;