im gettin this really annoying error message. I know Im only new to this but it seems the type of thing I could figure out. Can anyone show me where im going wrong please?
The message at run time is: Debug Assertion Failed! Program: .... File: c:\program files\microsoft visual studio 10.0\vc\include\vector Line: 932 Expression: Vector subscript out of range
and the code is
#include<iostream>
#include<vector>
using namespace std;
struct Things {
string name;
string color;
string poison;
string burns;
double height;
};
typedef vector<Things> Forest;
void read_data(Forest& v) {
int n;
cin >> n;
for (int i = 0; i < n; i) {
cout << "DINTRE" << endl;
cin >> v[i].name;
cout << v[i].name << endl;
}
}
int count(const Forest& v, string name, string color, string poison, string burns, double height) {
int x = v.size();
int cont = 0;
for (int i = 0; i < x; i) {
if (v[i].name == name or name == "*") {
if (v[i].color == color or color == "*") {
if (v[i].poison == poison or poison == "*") {
if (v[i].burns == burns or burns == "*") {
if (v[i].height >= height or height == 0) cont;
}
}
}
}
}
return cont;
}
int main() {
Forest v;
read_data(v);
vector<string> pregunta(4);
while (cin >> pregunta[0]) {
for (int i = 1; i < 4; i) {
cin >> pregunta[i];
}
double height;
cin >> height;
cout << count(v, pregunta[0], pregunta[1], pregunta[2], pregunta[3], height) << endl;
}
}
CodePudding user response:
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.
CodePudding user response:
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';
}
}
CodePudding user response:
The size of vector, passed in read_data(), is 0 i.e. it's an empty vector. In read_data(), when you doing v[i] that means you are trying to access ith element of vector v which does not exists. Hence, you are getting the error. To fix this, create an object of type Things, take user input and push_back() it in vector v:
for (int i = 0; i < n; i) {
Things x;
cout << "DINTRE" << endl;
cin >> x.name;
cout << x.name << endl;
v.push_back(x);
}
