Go Premium for a chance to win a PS4. Enter to Win


C++ STL part 1: Vectors

Published on
9,512 Points
1 Endorsement
Last Modified:

1. What is C++ STL?

STL stands for Standard Template Library and is a part of standard C++ libraries. It contains many useful data structures (containers) and algorithms, which can spare you a lot of the time. Today we will look at the STL Vector.

2. C++ classic fixed size arrays

Everyone who has ever programmed in C++, has came across the classic fixed-size array. Here is an example.
//declare array (indexes are from 0 to 999 (1000 elements), be careful)
int arr[1000];

int num;

cout << "How many numbers will you write?" << endl;
cin >> num;

//read NUM integers and write them into array
for(int i=0; i<num; ++i) {
	cin >> arr[i];

Open in new window

In this example we have read num elements from the user and stored them into array. If we wanted to read more than 1000 values, we would overflow the array, resulting in undefined behaviour. The place for 1000 integers is defined when program is compiled and cannot be changed at runtime. This can be overcame by dynamic memory allocation. (See below)

3. C++ dynamic memory allocation arrays

Take a look at the following code snippet:
int num;

cout << "How many numbers will you write?" << endl;
cin >> num;

int *arr=new int[num];
for (int i=0; i<num; ++i) {
	cin >> arr[i];

delete arr[];

Open in new window

Firstly, we ask an user to tell us, how many numbers he wants to input and then we read them. This is a lot better, we can allocate the required amount of memory at runtime instead of declaring fixed array of a very big amount of integers, hoping user won't overflow the array with his choice how many numbers he wants to input. Don't forget to delete the allocated array at the end of your code and free the used memory.

The more modern way of doing this is a vector, which can change its size during the program execution. We will take a look at it in the next chapter.

4. C++ STL Vector

Vectors are very similar data structures as arrays, the difference is that they reallocate themselves when they are about to overflow. Their way of use is also very similar. But first, to use C++ Vector, we need to include STL vector library. It is as simple as that:
#include <vector>

Open in new window

Now we can use vectors in our code. Let see some examples:
vector<int> first; //creates empty vector of integers
vector<int> second(100, 0); //creates vector with 100 zeroes
vector<float> third(3, 5.3); //creates vector, with three values 5.3
vector<int> fourth(second); //creates a copy of second vector

Open in new window

At first, we defined 4 vectors (see the explanations). The different ways of declaring a vector are called allocators.

5. Adding (appending) elements to Vector

To add one element to the back of the vector, you can use the vector.push_back(value). See the example below. It "pushes back" elements to the back of the vector until user inputs 0 (zero).
vector<int> first; //creates empty vector of integers

//read until user writes 0
int read;
while(true) {
	cin >> read;
	if (read==0) break;

Open in new window

6. Counting the number of elements

This is a simple thing to do and a huge bonus over classic arrays, where you have to keep track of number of elements in a special variable (integer). Here it is just as simple as calling vector.size(). See the example. It displays the count of numbers in the previous example.
cout << "You have written " << first.size() << " numbers.";

Open in new window

7. Accessing / changing the elements

There are a number of ways of doing this. Let the examples speak for themselves. The code is well commented.
cout << "Last number was: " << first.back();
first.back()=10; //change the last number to 10

cout << "First number was: " << first.front();
first.front()=10; //change the first number to 10

cout << "Third element was: " << first[2];
cout << "Third element was: " << first.at(2);
first[2]=10; //Change third number to 10
first.at(2)=10; //Change third number to 10

Open in new window

What is the difference between [n] and .at(n)?
If there are less elements in the vector than n, then .at(n) will throw an exception (aka. report an error), while [n] will produce undefined result.

8. Clearing the vector

In some cases, you need to empty (erase all the elements) of the whole vector. This is simple thing to do.

Open in new window

9. Removing the last element

Simple. The same way you called vector.push_back(value), call vector.pop_back().

Open in new window

10. Why to use STL Vector?

With STL Vectors, many things were made simpler. Use it!

11. What about the speed of execution?

If you turn on compiler level 2 or 3 optimisation, benchmarks show us that there is no or minimum speed drawback. Great, you have no reason to avoid vectors!
g++ code.cpp -O3

Open in new window

12. Want to know more?

If I got your attention and you want to know more about the STL Vector, check the C++ reference page: http://www.cplusplus.com/reference/stl/vector/vector/

To be countinued... (STL part 2: Strings)
1 Comment
LVL 49

Expert Comment

Good article!  You explained it very well.  I look forward to additions to this series.

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Join & Write a Comment

The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

Keep in touch with Experts Exchange

Tech news and trends delivered to your inbox every month