I’m fairly new to C++ especially STL. I’m trying to pass a vector as argument to a function, but it causes the application to crash. I’m using Code::Blocks and MingW. Here is a simple code.
#include <iostream>
#include <vector>
using namespace std;
void foo(const vector<int> &v)
{
cout << v[0];
}
int main(){
vector<int> v;
v[0] = 25;
foo(v);
return 0;
}
Thanks!
It crashes because you write past the end of the vector with
v[0]– that’s undefined behaviour. Its inital size is 0 if you do nothing. (You subsequently read the same too, but all bets are off well before that point).You probably wanted to do:
Or maybe:
If you use
v.at(n)instead of the [] operator you will get exceptions thrown rather than undefined behaviour.