更改为:
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...
}
备选:
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...
}
使用['性病::设置'](http://en.cppreference.com/mwiki/index .php?title = Special%3ASearch&search = std%3A%3Aset)而不是原始整数数组。 –
你可能会考虑插入一个'std :: set'并检查结果。即使是最小的变化,使用'std :: find'代替循环。另外请注意,如果在目前设置的元素中找不到元素,您正在读取未初始化的数据。 – chris
或者您只需在数值再次输入后引入'break'。但是你不会初始化你的错误,因此你的* exists *检查(即'j'循环)的上限应该是'i'而不是'arr_size',因为在大于'i'的每个元素中都可以是内。 –