矢量下标超出范围的错误在c ++ [英] vector subscript out of range error in c++

查看:398
本文介绍了矢量下标超出范围的错误在c ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图写一个程序,它接受n个整数的输入,并找出在给定输入中出现最大次数的那个。我试图运行程序的t案件。
为此,我实现了一个计数排序类似的算法(可能是一个bit naiive),计算输入中每​​个数字的出现次数。如果有多个数字具有相同的最大出现,我需要返回那些中较小的。为此,我实现了排序。

我面临的问题是,每次我在Visual C ++上运行程序时,我得到一个错误,告诉向量下标超出范围。在Netbeans下,它生成一个返回值为1并退出。请帮我找到问题

I am trying to write a program that takes an input of of n integers, and finds out the one that occurs the maximum number of times in the given input. I am trying to run the program for t cases. For this, I have implemented a counting sort like algorithm (perhaps a bit naiive), that counts the number of occurrences of each number in the input. In case there are multiple numbers with the same maximum occurrence, I need to return the smaller among those. For this, I implemented sorting.
The issue I am facing is, that every time I run the program on Visual C++, I am getting an error that tells "vector subscript out of range". Under Netbeans, it is generating a return value of 1 and exiting. Please help me find the problem

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


推荐答案

a.clear()向量没有任何成员,其大小为0。

After a.clear() the vector doesn't have any members, and its size is 0.

添加对 a.resize(n),使其大小合适。您还需要将 buff 调整为所需的大小。

Add a call to a.resize(n) to make it the proper size. You also need to resize buff to whatever size it needs to be.

这篇关于矢量下标超出范围的错误在c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆