我想寫一個程序,需要輸入的n個整數,並找出出現在給定的輸入的最大次數的程序。我正在嘗試運行t案例。 爲此,我實現了一種類似於算法的計數排序(可能有點令人厭煩),它計算輸入中每個數字的出現次數。如果有多個數字具有相同的最大值,我需要返回其中較小的數字。爲此,我實施了排序。
我面對的問題是,每次我在Visual C++上運行程序時,都會收到一個錯誤,告知「向量下標超出範圍」。在Netbeans下,它產生1的返回值並退出。請幫我看看這個問題矢量下標超出範圍錯誤在C++
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int findmax(vector<int> a, int n)
{
int i,ret;
ret = 0;
for (i = 0; i <n; i++)
{
if (a[i] > ret) {
ret = a[i];
}
}
return ret;
}
int main() {
int i = 0, j = 0, k = 0, n,m,r1,r2;
vector<int> a;
int t;
vector<int> buff;
cin>>t;
while(t--) {
cin>>n;
a.clear();
buff.clear();
for (i = 0; i < n; i++) {
cin>>a[i];
}
sort(a.begin(),a.end());
m = findmax(a,n);
for (j = 0; j < m+1; j++) {
buff[a[j]] = buff[a[j]] + 1;
}
k = findmax(buff,m+1);
for (i = 0; i < m+1; i++) {
if (buff[i] == k) {
r1 = i;
r2 = buff[i];
break;
}
}
cout<<r1<<" "<<r2<<endl;
}
return 0;
}
這可以通過調試器解決,或者只需添加一堆額外的'cout'語句來檢查所有索引。 – 2012-02-01 18:04:30
[C++ Assertion在運行時向量上失敗表達式:向量下標超出範圍]的可能重複(http://stackoverflow.com/questions/5736813/c-assertion-failed-on-vector-at-runtime-expression-vector -subscript-out-of-ra) - 你永遠不會增加你的vector的大小,所以它是'0' – 2012-02-01 18:04:51
@OliCharlesworth:對不起,使用調試器是沒有用的 – hytriutucx 2012-02-01 18:05:47