Vectors

NOTE: This article is part of a C++ guide, therefore only C++ code will be displayed.

Vectors

Vectors in C++ are containers that store elements in a certain order. They can have duplicate elements and can change in size.

Initialization

Vectors can be initialized in many ways:

#include <bits/stdc++.h>
using namespace std;

int main(){
    // this creates an empty list of numbers
    vector<int> numbers;

    // this creates a list of 5 numbers with unkown values
    vector<long long> other_numbers(5);

    // this list has 7 elements which are all set to 100
    vector<int> my_grades(7,100);
}

Accessing and changing values

Accessing a vector has the following syntax:

#include <bits/stdc++.h>
using namespace std;
int main(){
    vector<int> numbers(5,0); // numbers = {0,0,0,0,0}

    // 0-based indexing
    numbers[2] = 5; // numbers = {0,0,5,0,0}

    cout << numbers[2] << endl; // prints 2

    numbers.push_back(7); // adds an element to the end of the list; numbers = {0,0,5,0,0,7}

    // numbers.size() is the number of elements in the list
    for(int i = 0;i < numbers.size();i++){
        // here all the numbers would get printed like this: 0 0 5 0 0 7
        cout << numbers[i] << " ";
    }
    cout << "\n";
}

getting a list of numbers from input

A vast number of problems have an input format similar to the following:

Input consists of two lines. The first has an an integer nn (1n1051\le n\le10^{5}) denoting the number of elements, while the second line of input contains nn number of elemements.

Example Input:

5
2 5 10 2 8

There are two ways to get these numbers in vectors:

The first way is by making a list and then adding elements to the end of the list like so:

#include <bits/stdc++.h>
using namespace std;
int main(){
    int n;
    cin >> n;

    vector<int> numbers;

    int temporary;
    for(int i = 0;i < n;i++){
        cin >> temporary;
        numbers.push_back(temporary);
    }
    // solution to the problem
    // ...
}

An easier method is to create the list to be nn elements in length and then use cin to put the elements there directly

#include <bits/stdc++.h>
using namespace std;
int main(){
    int n;
    cin >> n;

    vector<int> numbers(n);

    for(int i = 0;i < n;i++){
        cin >> numbers[i];
    }
    // solution to the problem
    // ...
}

Practice problems

Additional resources

Copied to Clipboard