gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 03:16:26 27 4
gpt4 key购买 nike

问题是(见输出),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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com