Search code examples
c++stdvector

why does my c++ program not work when I trying to print an element of a vector?


My c++ programs are not working when using vectors. The code of my program is given below, I am able to compile the file but when I try to run it just throws an error.

#include <iostream>
#include <vector>

int main(){
    std::vector<int> a;
    a[0]= 10;

    std::cout << a[0] << std::endl;

    a[0]= a[0]*10+5;
    std::cout << a[0] << std::endl;
}

I have tried commenting the lines with vector and writing another program in the same file but as soon as I uncomment the vector lines it throws an error on running.

I using VScode and MINgw.


Solution

  • The line:

    std::vector<int> a;
    

    creates an empty vector without any element.

    According to cppreference: https://en.cppreference.com/w/cpp/container/vector/operator_at

    a[0]= 10;
    

    returns a reference to the element at a specified location - 0. No bounds checking is performed.

    It does not mean: "Create element at position 0 and assign 10" - it assumes you have already created an element and saved new value to it"

    What you want to do is:

    std::vector<int> a; // create empty vector
    a.push_back(10);    // add new value to vector
    

    or alternatively

    std::vector<int> a (1); //Constructs the container with count default-inserted instances of T (0 in our case)
    
    std::cout << a[0] << std::endl; // It should return 0
    
    a[0] = 10; 
    
    std::cout << a[0] << std::endl;// It should return 10 now