-1
當此經過for循環中,我一直有錯誤消息調試斷言失敗向量下標越界
「調試斷言失敗。矢量下標越界。」
所以我跟蹤的for循環,而當輸入爲
5
1 100
2 100
3 80
4 60
5 80
發生錯誤時我== 2,但我不知道什麼是錯後,我== 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;
}
爲什麼不簡單地打印'temp'? –
@MuhammadAhmad這也是一種選擇是這種情況。但是,一般來說,這個選項並不相同,所以如果OP想要打印推向矢量的對象,這是正確的方法。 – 2016-09-28 13:17:00
Ohhhh非常感謝我錯過了@Satus – Hmmmmm