我正在尝试编写一个玩强力球彩票的模拟器,其中程序会要求5
个数字(又名白球)并输入到6
元素数组和另一个数字(红色强力球)放入第 6
个元素中。
我需要弄清楚如何测试前 5
元素中的重复项,但第 6
元素不需要是唯一的。
我有一个循环,我认为可以工作,但它甚至不执行并且相当困惑。
是否有更有效的方法来测试重复项,可能涉及 bool 标志?
const int PBALLAMOUNT = 6;
const int PBMAX = 69;
const int PBMIN = 1;
const int REDMAX = 26;
cout << "Enter the numbers you want to use for the white powerballs" << endl;
for (int k = 0; k < PBALLAMOUNT - 1; k++)
{
cin >> pBallNums[k];
while (pBallNums[k] < PBMIN || pBallNums[k]>PBMAX)
{
cout << "Invalid input! Please enter different numbers between 1 and 69" << endl;
cin >> pBallNums[k];
}
}
bool dup = false;
for (int i = 0; i < PBALLAMOUNT - 1; i++)
{
for (int j = i + 1; j < PBALLAMOUNT - 1; j++)
{
while (!dup)
{
if (pBallNums[i] == pBallNums[j])
{
cout << "Please enter a unique number from the others in your PowerBall number selection" << endl;
cin >> pBallNums[i];
}
}
}
}
cout << "And what would you like for your redball" << endl;
cin >> pBallNums[5];
while (pBallNums[5] < PBMIN || pBallNums[5] > REDMAX)
{
cout << " The red powerball needs to be between 1 and 26: ";
cin >> pBallNums[5];
}
我基本上只需要它来提醒用户,如果他们已经在数组中输入了一个数字,并提供另一个 std::cin >> pBallNums
语句,但实际结果是在您之后什么也没有发生输入数字。
最佳答案
"I basically just need it to alert the user if they've already entered a number into the array and offer another
cin >> pBallNums
statement."
在这种情况下,只需使用 std::set
并使用它的 std::set::emplace
方法将用户输入存储到集合中。
来自 cppreference.com ,
template< class... Args >
std::pair<iterator,bool> emplace( Args&&... args );
std::set::emplace
Returns a pair consisting of an iterator to the inserted element, or the already-existing element if no insertion happened, and a bool denoting whether the insertion took place. True for Insertion, False for No Insertion.
只需将此信息用于您的案例,然后再次循环以获取下一个用户输入。
这里是示例代码( See Live ):
#include <iostream>
#include <set>
int main()
{
std::set<int> mySet;
for(int loopCount{ 0 }; loopCount != 5; )// repeat until maximum loop count
{
int input; std::cin >> input; // user input
// get the std::pair<iterator,bool>
const auto pairIter = mySet.emplace(input);
// increment maximum loop count, if insertion successful
if (pairIter.second) ++loopCount;
}
for (const int userInput : mySet)
std::cout << userInput << " ";
return 0;
}
示例输入:
1
1
2
3
4
2
4
3
5
输出:
1 2 3 4 5
关于c++ - 测试用户输入数组中的重复项的最有效方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56029286/