这是我的一大堆代码。我试图循环向量,如果有重复,我想输出“每个数字必须不同”。问题是当矢量元素不相同时,它仍然输出“每个数字必须不同”。我做错了什么?
bool endLoop = false;
for(int g = 0; g < guessVec.size(); ++g){
for( int j = 1; j < guessVec.size(); ++j){
if(guessVec.at(g) == guessVec.at(j)){
endLoop = true;
}
else if( guessVec.at(g) != guessVec.at(j)){
endLoop = false;
}
}
if(endLoop){
cout << "Each number must be different.";
break;
}
答案 0 :(得分:0)
bool endLoop = false;
for(int g = 0; g < guessVec.size(); ++g)
{
for(int j = g + 1; j < guessVec.size(); ++j) //<-- j can start from 'g + 1'
{
if(guessVec.at(g) == guessVec.at(j))
{
endLoop = true;
break; //<-- you can break the loop once you discovered a duplicate
}
//else if( guessVec.at(g) != guessVec.at(j))
//{
// endLoop = false;
//}
}
if(endLoop == true)
{
cout << "Each number must be different.";
break;
}
}