Vectors Recap
In this chapter, we learned how to work with vectors in C++. We found out that:
- We can create a vector using curly braces
{}
and elements separated by commas. For example:std::vector list = {1, 2, 3, 3};
- We access vector elements using their indices, which start at 0. For example:
std::cout << list[0];
prints the first element of the vectorlist
. - For safer access to elements, we can use the
at()
method. For example:list.at(0)
. - We can easily change vector elements using their indices. For example:
list[3] = 4;
sets the fourth element of the vectorlist
to the value 4. - Using the
push_back()
method, we can add new elements to the end of the vector. For example:list.push_back(5)
adds the value 5 to the end of the vector. - Using the
size()
method, we can find out the number of elements in the vector. For example:size = list.size()
stores the number of elements in the vector list into the variablesize
. - Vectors can contain other vectors as their elements, which allows us to create nested vectors. For example:
std::vector<std::vector<int>> nestedArray = {{1, 2}, {3, 4}, {5, 6}}
. - Text strings (std::string) can also be considered as character arrays, which we can access using their indices. For example:
std::string text = "Programming";
andchar firstChar = text[0];
stores the first character'P'
into the variablefirstChar
.
Congratulations on completing the lesson about vectors! In the next lesson, we'll look at loops and their use in C++. Get ready for the next step in your programming adventure!
Instructions
When you're ready, move on to the next lesson!
Start programming for free
10/10