c++ - 数组元素中的 C++ 逻辑错误,而数组作为构造函数中的参数传递

标签 c++ arrays

问题是(见输出),obj2 元素看起来像在 main 方法中传递的 obj2 和 obj1 的并集。还有为什么 obj1 和 obj2 总是以 1,2 开头,不管 no 是什么。的以及它们中存在哪些元素。我现在在这个问题上花了整整一个晚上,之前还有其他问题:In C++ program which passes array in constructor, execution stops无论这个问题在你看来多么微不足道。我将不胜感激任何帮助..请..而不是建议 c++ 库中可用的复杂而有效的解决方案,请尝试建议我作为新手出错的地方:/

感谢期待!

 //partial "integerset.h"

 class IntegerSet{
  public :
         IntegerSet( int [] );
         void insertEl(int);
         void deleteEl(int); //delete is a keyword, can't be identifier
         void printSet();
  private :
         int setArr[20];//no.s can be 1 to 20            
 };

 //partial "integerset.cpp"

 //libraries included

IntegerSet :: IntegerSet( int arr[] ){ 
       for(int i = 0; i < 20; i++)
               setArr[i] = 0; //for consistent data at start,avoid garbage
       for( int i = 0; i < 20; i++){
            if ( arr[i] >= 1 && arr[i] <= 20)
               this->insertEl(arr[i]);           
       }
}
void IntegerSet :: insertEl(int item){
            if ( setArr[item-1] != 1) //-1 so that 5 is checked at 4th position, etc.
                setArr[item-1] = 1; //set 4th array element to 1 if item = 5 
 }
void IntegerSet :: deleteEl(int item){ //delete is a keyword, can't be identifier
            if ( setArr[item-1] != 0 )
               setArr[item-1] = 0;
}
void IntegerSet :: printSet(){
    for ( int i = 0; i < 20; i++){
          if( this->setArr[i] == 1) 
                cout<<i+1<<" "; // + 1 important so that 2 displayed at 1st position
    }
}

   //partial "main.cpp"


  int main(){
      int a[] = {9,10,15,18,19};
      int b[] = {1,3,12,14,15};
      IntegerSet obj1(a);   
      IntegerSet obj2(b);
      cout<<"\nintial obj1\n";
     obj1.printSet();  
     cout<<"\ninitial obj2\n";
     obj2.printSet(); 

    obj1.deleteEl(18);
    cout<<"\nafter deletion of 18 \n";
    obj1.printSet();
    obj1.insertEl(7);
    cout<<"\nafter insertion of 7\n";
    obj1.printSet();

    system("PAUSE");
    return EXIT_SUCCESS;
  }

 //here's the output

 ![output of program][1]


  http://tinypic.com/view.php?pic=25uiceo&s=5

最佳答案

您将垃圾传递给您的构造函数,因为您的输入数组仅包含 5 个元素,但您对它们进行索引时就好像它们包含 20 个元素一样。

改变:

 int a[] = {9,10,15,18,19};
 int b[] = {1,3,12,14,15};

到:

 int a[20] = {9,10,15,18,19};
 int b[20] = {1,3,12,14,15};

请注意,未显式初始化的元素将包含 0,因此现在相当于:

 int a[20] = {9,10,15,18,19,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
 int b[20] = {1,3,12,14,15,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};

关于c++ - 数组元素中的 C++ 逻辑错误,而数组作为构造函数中的参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16732180/

相关文章:

c++ - 填充指向 vector 的 vector

ruby-on-rails - 按父对象对评论进行分组,按最旧的评论对父对象进行排序

Python 文件加密

java - Java 数组是类实例吗?

c++ - 从多个 2D 点重建 3D 点?

C++11 std::condition_variable:我们可以将锁直接传递给通知线程吗?

arrays - 查找数组中是否存在两个互质数

Javascript:将值列表转换为对象集

c++ - OpenCV - 扭曲透视

c++ - BlueZ5 : Event when inbound pairing is complete