c++ Faliure on vector at runtime: vector subscript out of range
consider the first line that tries to modify the data in v:
cin >> v[i].name;
This is occurring while v is an empty vector (has a size of 0). To add elements to the end of a vector you need to use push_back
:
string name;
cin >> name;
v.push_back(name);
the square brackets ("[]") are for accessing an element that already exists in the vector.
In read_data
you access the std::vector<Things>
(Forest
) v
out of bounds (out of range) since the vector is empty.
You could resize it after having asked the user for how many elements that should be entered.
Example:
void read_data(Forest& v) {
int n;
if(std::cin >> n && n > 0) v.resize(n); // resize
for (int i = 0; i < v.size(); ++i) { // use v.size() here
std::cout << "DINTRE\n";
std::cin >> v[i].name;
std::cout << v[i].name << '\n';
}
}
or simpler by using a range-based for loop:
void read_data(Forest& v) {
int n;
if(std::cin >> n && n > 0) v.resize(n);
for(auto& thing : v) {
std::cout << "DINTRE\n";
std::cin >> thing.name;
std::cout << thing.name << '\n';
}
}