C++ STL part 1: Vectors

AID: 2800
  • Status: Published

2390 points

  • ByRok-Kralj
  • TypeGeneral
  • Posted on2010-04-04 at 02:49:23
Awards
  • Community Pick
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];
}
                                    
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:

Select allOpen 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[];
                                    
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:

Select allOpen 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>
                                    
1:

Select allOpen 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
                                    
1:
2:
3:
4:

Select allOpen 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;
	first.push_back(read);
};
                                    
1:
2:
3:
4:
5:
6:
7:
8:
9:

Select allOpen 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.";
                                    
1:

Select allOpen 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
                                    
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:

Select allOpen 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.
first.clear();
                                    
1:

Select allOpen in new window


9

Removing the last element


Simple. The same way you called vector.push_back(value), call vector.pop_back().
first.pop_back();
                                    
1:

Select allOpen 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
                                    
1:

Select allOpen 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)
Asked On
2010-04-04 at 02:49:23ID2800
Tags

C++

,

STL

,

array

,

vector

,

size

,

push_back

,

pop_back

,

erase

,

at

Topic

C++ Programming Language

Views
1310

Comments

Expert Comment

by: DanRollins on 2010-04-05 at 14:10:21ID: 12708

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

Add your Comment

Please Sign up or Log in to comment on this article.

Join Experts Exchange Today

Gain Access to all our Tech Resources

Get personalized answers

Ask unlimited questions

Access Proven Solutions

Search 3.2 million solutions

Read In-Depth How-To Guides

1000+ articles, demos, & tips

Watch Step by Step Tutorials

Learn direct from top tech pros

And Much More!

Your complete tech resource

See Plans and Pricing

30-day free trial. Register in 60 seconds.

Loading Advertisement...

Top C++ Experts

  1. jkr

    261,219

    Guru

    1,000 points yesterday

    Profile
    Rank: Savant
  2. sarabande

    121,084

    Master

    3,800 points yesterday

    Profile
    Rank: Sage
  3. Infinity08

    54,855

    Master

    0 points yesterday

    Profile
    Rank: Genius
  4. ambience

    50,164

    Master

    0 points yesterday

    Profile
    Rank: Sage
  5. Zoppo

    48,382

    0 points yesterday

    Profile
    Rank: Genius
  6. evilrix

    48,358

    80 points yesterday

    Profile
    Rank: Genius
  7. satsumo

    22,400

    0 points yesterday

    Profile
    Rank: Guru
  8. tampnic

    19,040

    0 points yesterday

    Profile
    Rank: Master
  9. phoffric

    16,596

    0 points yesterday

    Profile
    Rank: Genius
  10. DanRollins

    16,330

    0 points yesterday

    Profile
    Rank: Genius
  11. duncan_roe

    14,400

    0 points yesterday

    Profile
    Rank: Genius
  12. gtokas

    12,700

    0 points yesterday

    Profile
    Rank: Wizard
  13. AndyAinscow

    12,132

    0 points yesterday

    Profile
    Rank: Genius
  14. mccarl

    9,600

    0 points yesterday

    Profile
    Rank: Wizard
  15. TommySzalapski

    8,800

    0 points yesterday

    Profile
    Rank: Genius
  16. pepr

    7,824

    0 points yesterday

    Profile
    Rank: Genius
  17. kaufmed

    7,168

    0 points yesterday

    Profile
    Rank: Genius
  18. Thommy

    6,700

    0 points yesterday

    Profile
    Rank: Wizard
  19. ubound

    6,550

    0 points yesterday

    Profile
    Rank: Master
  20. kuroji

    6,000

    0 points yesterday

    Profile
  21. for_yan

    6,000

    0 points yesterday

    Profile
    Rank: Genius
  22. mrwad99

    4,600

    0 points yesterday

    Profile
    Rank: Wizard
  23. masheik

    4,572

    0 points yesterday

    Profile
    Rank: Guru
  24. Orcbighter

    4,332

    0 points yesterday

    Profile
    Rank: Master
  25. ozo

    4,300

    0 points yesterday

    Profile
    Rank: Savant

Hall Of Fame