noobtuts

C++ Tutorial for noobs - Part 9: Lists

...Back to Part 8: Arrays

Since we already know about Arrays, this part will be really easy.

Motivation

As mentioned before, we often come across situations where we have five, ten or maybe a hundred things that we want to store somewhere. The problem about Arrays was that we always have to know the final size before creating them, and there is no way to make them bigger.

Using a list solves that problem by being dynamic, which means that we can create a list without knowing the final size, and we can add and remove as many things as we want without worrying about the size.

std::vector

In C++ there are several list types that we can use. For beginners, the most useful one is the std::vector, so let's use that one.

Creating a List

Let's get to the point by creating a list. At first we have to include the std::vector thing once:

#include <vector>

Now we can actually create a list like so:

std::vector<float> v;

This creates a std::vector of type float with the name v. Being of type float means that it can hold float values like 0.123f and so on. If we would want a list of boolean values, we could use:

std::vector<bool> v;

instead.

Adding Elements to a List

Now that we created our list of type float, we can easily add values to it with the push_back function like so:

std::vector<float> v;
v.push_back(0.0f);
v.push_back(1.0f);
v.push_back(2.0f);

Push-back means that it always adds the element to the back of the list, hence our list currently looks like this:

Remember: at this point we can add as many values to the list as we want, there is no limit.

Accessing List Elements

We can access list elements the same way that we access Array elements like so:

std::cout<<v[0];
std::cout<<v[1];
std::cout<<v[2];

Note: we can also access list elements by using v.at(0).

Size

As mentioned before, the cool thing about lists is that we don't have to know the size of the it, because the list keeps track of that for us already. We can find out a list's size like this:

std::cout<<v.size();

Looping

As with Arrays, we can also use the for-loop to go through all elements in a list. Since we already know the size() function, we can now loop through any kind of list like so:

for (int i = 0; i < v.size(); ++i) {
    std::cout<<v[i];
}

Removing from a List

Let's say we have a list of zoo animals like this one:

Which we can create very easily:

#include <vector>
#include <string>

std::vector<std::string> v;
v.push_back("Dog");
v.push_back("Cat");
v.push_back("Zebra");

And because the Zebra is really smart, it managed to escape from the zoo somehow. Now it's our turn to keep our list correct by removing the Zebra from the position 2 in the list:

v.erase(v.begin() + 2);

The important part is to keep in mind that the erase() function always needs to know the beginning of the list, hence we use v.begin() + 2 and not just 2.

Continue to Part 10: Strings...