此代码显示错误“stu unclared”??我该怎么办

时间:2013-05-20 06:28:26

标签: c++ arrays testing dynamic

我知道这个错误是因为我已经在for循环范围内声明了stu但它是程序的必要性。我想为每个测试用例声明一个数组(测试用例应该一次全部输入)。建议我实现这一目标的方法。是动态记忆的另一种选择。

#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
int main()
{
    int t;
    cin>>t;
    int n[t],g[t];
    int m =0;
    for(int w=0;w<t;t++)
    {
        cin>>n[w]>>g[w];
        int stu[n[w]];
        for(int i=0;i<n[w];i++)
        {
            cin>>stu[i];
        }

    }    
    while(m<t)
    {
        int a,b;    
        int e;
        e = (n[m]*(n[m]-1))/2;
        int diff[e];
        if (g[m]=1)
        {
            cout<<0<<endl;
            return 0;
        }
        b=*(min_element(stu,stu+n[m]-1));
        a=*(max_element(stu,stu+n[m]-1));
        if (g[m]=n[m])
        {
            cout<<a-b<<endl;
            return 0;
        }
        int z = 0;
        for(int j=0;j<(n[m]-1);j++)
        {
            for(int k=(j+1);k<n[m];k++)
            {
                diff[z]=abs(stu[j]-stu[k]);
                ++z;
            }
        }        
        cout<<*(min_element(diff,diff+e-1))<<endl;
        ++m;
    }    
    cin.ignore();
    cin.get();
    return 0;
} 

2 个答案:

答案 0 :(得分:3)

您在stu循环内声明for,因此它仅限于循环的范围。然后尝试在循环之外使用它,在未声明的地方。

for(int w=0;w<t;t++)
{
  ...
  int stu[n[w]]; // Beware: stu is a VLA. Non-standard C++.
  // OK to use stu here
  ...
}    
// stu doesn't exist here

另请注意,标准C ++不支持variable length arrays(VLA),这是您尝试在stu声明中使用的内容,以及此处:

int t;
cin>>t;
int n[t],g[t];

您可以按std::vector<int>替换这些数组:

#include <iostream>
#include <vector>

int main()
{
  int t=0;
  cin>>t;
  std::vector<int> n(t);
  std::vector<int> g(t);
  std::vector<int> stu ...;

}

答案 1 :(得分:0)

该行

int stu[n[w]];

在一个街区内,在那个街区之外,它不会被看到。你应该把它移出块,但这样做当然你不能使用n[w],而是循环var。您可以限制n[w]可以拥有的最大值,例如

#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
const int MAXV = 100;
int main()
{
  int t;
  cin>>t;
  int n[t],g[t]; // <- supported by some compiler, but not std
  int m =0;
  int stu[MAXV];
  for(int w=0;w<t;t++) {
      cin>>n[w]>>g[w];
      for(int i=0;i<n[w] && i < MAXV;i++) {
        cin>>stu[i];
      }
  }    
  while(m<t) {
      int a,b;    
      int e;
      e = (n[m]*(n[m]-1))/2;
      int diff[e];
      if (g[m]==1) {
        cout<<0<<endl;
        return 0;
      } 
      b=*(min_element(stu,stu+n[m]-1));
      a=*(max_element(stu,stu+n[m]-1));
      if (g[m]==n[m]) {
        cout<<a-b<<endl;
        return 0;
      }
      int z = 0;
      for(int j=0;j<(n[m]-1);j++) {
        for(int k=(j+1);k<n[m];k++) {
          diff[z]=abs(stu[j]-stu[k]);
          ++z;
        }
      }        
      cout<<*(min_element(diff,diff+e-1))<<endl;
      ++m;
  }    
  cin.ignore();
  cin.get();
  return 0;
}        

(我假设你的意思是==而不是=,我已经在有条件的情况下解决了几项任务,但是我没有测试代码是否符合您的预期:它只是使用g ++进行编译,但不能与其他编译器一起编译,请参阅代码中的注释)

相关问题