I have a program for school to make and i thought i'd use vectors, everything went smoothly but at the end I saw that function in my program that pushes elements to vector of classes do it only inside function, out of function the vector has the same size.
I wrote a small test code to show it.
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cassert>
using namespace std;
class Player {
public:
int i = 1;
Player() {}
};
void pb(vector<Player> v) {
v.push_back(Player());
cout << v.size() << endl;
}
int main()
{
vector<Player> v;
v.push_back(Player());
cout << "1st element i = " << v[0].i << endl;
cout << "vector size: " << v.size() << endl;
pb(v);
cout << "Second element i = " << v[1].i << endl;
cout << "vector size: " << v.size() << endl;
}
The code send error "Vector subscript out of range" because I try to enter the non-existent v[1] that should exist because in function I did use push_back().
Can someone explain to me why does it happen, and how would I do it with the usage of pointers if I can do so?