0

如果数组包含这些索引作为其元素,我正在尝试将索引处的集合元素设置为 1。数组大小为 20,即索引 0 到 19

对于前 -

 int myArray[5] = {1,4,2}; //user input or statically defined in driver(main)
 int set[] = {0,1,1,0,1}; //successfully set in constructor
 IntegerSet intObj(set);//At a point, program stops execution. Any idea why?

这是部分代码

    //integerset.h 

    class IntegerSet{
          public :
              IntegerSet( int [] );
              .....
          private :
              int set[20];            
    };

  //integerset.cpp (header files included)

  IntegerSet :: IntegerSet( int arr[]){
       for(int i = 0; i <20; i++) //works fine (printed "test" in loop)
               set[i] = 0; //if not this then garbage elems set
       for ( int i = 0; arr[i] != '\0' ; i++ ) //works fine. (printed "test" in loop)
          set [arr[i]] = 1;        
       for ( int i = 0; i < 20; i++ ) //program stops execution here
           cout<<i<<"\t"<<set[i]<<"\n"; //tried to print "test" in loop,program crashed
  }

  //main.cpp (header files included)


int main(){
             int a[] = {1,3,0,12,14,15,'\0'}; // premature end??
             IntegerSet obj2(a);
             system("pause");
             return 0;
   }
4

2 回答 2

1

arr[i] != '\0'中,您的数组没有空终止符,因此循环继续并且索引元素通过数组的末尾。

最佳做法是使用std::arrayor std::vector。另一种选择是对您的代码进行以下修复:

template <int N>
IntegerSet :: IntegerSet(int (&arr) [N]) : set() {
       for (int i = 0; i < N ; i++)
          set [arr[i]] = 1;        
       for (int i = 0; i < 20; i++)
           cout<<i<<"\t"<<set[i]<<"\n";
  }
}
于 2013-05-24T03:54:42.517 回答
0

当您将数组解析为函数作为参数及其名称时,它指的是数组中第一个元素的地址。因此,在您的情况下,a 是一种 int *。因此,您需要将构造函数参数更改为 int *

于 2013-05-24T03:55:29.280 回答