C++ 如何用不同的值填充数组
我希望数组输入不能有两次相同的数字: 然而,这将有一个输出 “值存在,请重新输入:”; 两次。我如何检查它是否唯一,并且如果它之前已初始化,则仅显示一次C++ 如何用不同的值填充数组,c++,arrays,unique,C++,Arrays,Unique,我希望数组输入不能有两次相同的数字: 然而,这将有一个输出 “值存在,请重新输入:”; 两次。我如何检查它是否唯一,并且如果它之前已初始化,则仅显示一次 int main(){ int arr_size = 10; int value; int aArray[10]; for(int i=0;i<arr_size;i++) { cout<<"enter value of slot"<<i+1<<": ";
int main(){
int arr_size = 10;
int value;
int aArray[10];
for(int i=0;i<arr_size;i++)
{
cout<<"enter value of slot"<<i+1<<": ";
cin>>value;
for(int j=0;j<arr_size;j++){
if(value == aArray[j])
{
cout<<"value exist please re enter: ";
cin>>value;
}
else{
aArray[i] = value;
}
}
}
}
intmain(){
int arr_size=10;
int值;
国际原子能机构[10];
对于(int i=0;i更改为:
for(int i=0;i<arr_size;i++)
{
cout<<"enter value of slot"<<i+1<<": ";
while(1) { //You must keep reading until you have read a valid value
cin>>value;
bool alreadyPresent = false;
for(int j=0;j<i;j++){ //You only have to check against already inserted values!
//Before you were checking against uninitialized values!!
if(value == aArray[j])
{
alreadyPresent = true;
break; //I don't need to further iterate the array
}
}
if (alreadyPresent)
cout<< std::endl << value exists, please re enter: ";
else
break; //I can proceed with the next value, user has not to reenter the value
}
aArray[i] = value;
std::cout << std::endl; //next line...
}
用于(int i=0;i使用a代替原始整数数组)。您可以考虑插入到<>代码>::SET并检查其结果。即使是最小的更改,也要使用<代码> STD::查找< /COD>而不是循环。注意,如果到目前为止还没有找到元素,则您正在读取未初始化的数据。或者您只需介绍<代码>中断。但您不会初始化错误,因此也不会初始化存在性检查的上限(即j
-循环)应该是i
而不是arr\u size
,因为在每一个大于i
的元素中都可以有任何东西在里面。@isme另一个注意事项:应该使用const int arr\u size=10;
然后定义int array[arr\u size]
,因此以后您必须更改阵列的大小,您可以在一个位置进行更改,而且最重要的是,您将避免忘记在两个位置进行更改(这些错误很难检测,因为它们只会在运行时显示,有时会出现难以恢复原始错误的疯狂行为)@erburat是的,您肯定是对的,否则它只会检查第一个值。您应该删除第二个中断
,并将while(1)
更改为while(alreadyPresent)
将bool-alreadyPresent=true
移动到外部for-loop
。或者甚至在第一次获取值时在do…while-loop
中更改while-loop
。您可以使用bool-alreadyPresent=std::find(aArray,aArray+i,value)!=aArray+i;
而不是您自己的循环。@Jarod42是的,但使用库函数可能无助于OP理解其代码中的问题。@a_客人,我也添加了您的解决方案,它运行得更好,我同意
for(int i=0;i<arr_size;i++)
{
cout<<"enter value of slot"<<i+1<<": ";
bool alreadyPresent;
do { //You must keep reading until you have read a valid value
cin>>value;
alreadyPresent = false;
for(int j=0;j<i;j++){ //You only have to check against already inserted values!
//Before you were checking against uninitialized values!!
if(value == aArray[j])
{
alreadyPresent = true;
cout<< std::endl << value exists, please re enter: ";
break; //I don't need to further iterate the array
}
}
} while (alreadyPresent);
aArray[i] = value;
std::cout << std::endl; //next line...
}