调试断言失败的向量下标超出范围

时间:2016-09-28 13:04:28

标签: c++

当这经历for循环时,我一直有错误消息

  

“调试断言失败。向量下标超出范围。”

所以我跟踪了for循环,当输入是

5
1 100
2 100
3 80
4 60
5 80

当i == 2时发生错误。但在i == 2之后我不知道出了什么问题。 请给我一些建议。

错误发生在这一部分:

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;
        }
    }

这是我的代码:

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;
}

1 个答案:

答案 0 :(得分:0)

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;
    }
}

想象一下,如果您的if跳过了n次迭代。与访问value_counts[i].value时相比,您将访问数组范围之外,因为新值未添加到矢量中。

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