Hmmmmm Hmmmmm - 2 months ago 8
C++ Question

Debug assertion failed vector subscript out of range

When this goes through for loop, I keep having error message


"Debug assertion failed. vector subscript out of range."


so I tracked the for loop, and when input is

5
1 100
2 100
3 80
4 60
5 80


The error occurred when i == 2. But I have no idea what's wrong after i==2.
Please give me some advice.

the error is at this part:

for (int i = 0; i < childNum; i++) {
if (!IncrementIfFound(value_counts, info.gram_v[i])) {
Number_Counts temp(info.gram_v[i]);
value_counts.push_back(temp);
cout << "Value counts: " << value_counts[i].value << "\t" << value_counts[i].count << endl;
}
}


And this is my code :

struct Number_Counts
{
int value;
int count;
Number_Counts( int _element) { value = _element; count = 1; }
};

struct ChildInfo
{
vector<int> id_v;
vector<int> gram_v;
};

bool IncrementIfFound(vector<Number_Counts> &, int );

bool IncrementIfFound(vector<Number_Counts> &_Container, int _element)
{
for (int i = 0; i < _Container.size(); i++) {
if (_Container[i].value == _element) {
_Container[i].count++;
cout << "i : " << i <<" Container value: " << _Container[i].value << " counter: " << _Container[i].count
<< " size: " << _Container.size() << endl;
return true;
}
}
return false;
}

int main() {
vector<Number_Counts> value_counts;
ChildInfo info;
int childNum,id, gram = 0;

cin >> childNum;
for (int i = 0; i < childNum; i++) {
cin >> id >> gram;
info.id_v.push_back(id);
info.gram_v.push_back(gram);
}

for (int i = 0; i < childNum; i++) {
if (!IncrementIfFound(value_counts, info.gram_v[i])) {
Number_Counts temp(info.gram_v[i]);
value_counts.push_back(temp);
cout << "Value counts: " << value_counts[i].value << "\t" << value_counts[i].count << endl;
}
}

return 0;
}

Answer
for (int i = 0; i < childNum; i++) {
    if (!IncrementIfFound(value_counts, info.gram_v[i])) {
        Number_Counts temp(info.gram_v[i]);
        value_counts.push_back(temp);
        cout << "Value counts: " << value_counts[i].value << "\t" << value_counts[i].count << endl;
    }
}

Imagine if your if skips first n iterations. Than when you access value_counts[i].value, you will be accessing beyond array bounds, because new values were not added to vector.

        auto&& number_count = value_counts.back();
        cout << "Value counts: " << number_count.value << "\t" << number_count.count << endl;