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

int main() 
{
    vector<int> vect;
    vect[0]=1;
    vect[1]=1;
    vect[2]=1;

    for (int x : vect) 
        cout << x << " "; 

    return 0; 
}

I would like to know my fault here. I am new to c++ programming. Vectors is a very new concept to me.

little007
  • 3
  • 4
  • You create a `vector` of size `0`, then try to access three elements from it. This is UB. If you want three elements, then use `vect.resize(3)`, or use `push_back` to add elements. – ChrisMM Jun 10 '20 at 13:01
  • You cannot overwrite `vect[0] = 1` because 0th element doesnt exist yet. Use `push_back` instead. – freakish Jun 10 '20 at 13:01
  • `#include ` -- [Don't do this](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h). The appropriate headers are `` and ``. – PaulMcKenzie Jun 10 '20 at 13:11

3 Answers3

3

vect is an empty vector, so indexing into it invokes undefined behavior.

You could allocate enough space for vect, like this:

vector<int> vect(3);

Or you could push_back the elements:

vector<int> vect;
vect.push_back(1);
vect.push_back(1);
vect.push_back(1);
cigien
  • 57,834
  • 11
  • 73
  • 112
1

You try to access the elements at the positions 1, 2, and 3 however they do not exist yet.

To insert to new element try the method push_back:

vect.push_back(1);
vect.push_back(1);
vect.push_back(1);

Another option is to create a vector with three zeros:

std::vector<int> vect(3, 0);
vect[0]=1;
vect[1]=1;
vect[2]=1;

Or much more simple, create a vector with size 3 and all elements are assigned with 1:

std::vector<int> vect(3, 1);
curiouscupcake
  • 1,157
  • 13
  • 28
0

vect does not have allocated storage, so there isn't an arena to put the values on, hence undefined behaviour. You can get the allocated space of a container with capacity(), so in your case, vect.capacity() will return 0.

Furthermore, operator [] won't check the boundaries, so it will try to access to [ 2 ], even if its size is 0. To access checking boundaries use at().

Considering that, to solve the problem you will have to allocate space for the container (in your case, std::vector), that is, reserve an area of memory just for vect, vector offers different ways to modify its size, such as constructor, push_back, insert, resize, etc.

Note: if possible, avoid the use of using namespace std and <bits/stdc++.h>

Jose
  • 3,306
  • 1
  • 17
  • 22