Browse All Articles > C++ STL part 1: Vectors

```
//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];
}
```

In this example we have read ```
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[];
```

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.

```
#include <vector>
```

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
```

At first, we defined 4 vectors (see the explanations). The different ways of declaring a vector are called allocators.```
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);
};
```

```
cout << "You have written " << first.size() << " numbers.";
```

```
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
```

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.

```
first.clear();
```

```
first.pop_back();
```

```
g++ code.cpp -O3
```

To be countinued... (STL part 2: Strings)

Get access with a 7-day free trial.

SIGN UP

Not ready to sign up? Try a week for free to see if you belong

## Comments (1)

Commented: