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:
vector<int> v;
v.push_back(25);
foo(v);
Or maybe:
vector<int> v(1);
v.at(0) = 25;
foo(v);
If you use v.at(n)
instead of the [] operator you will get exceptions thrown rather than undefined behaviour.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With