测试用户输入数组中的重复项的最有效方法是什么?

What is the most efficient way to test for duplicates in a user inputted array?

本文关键字:有效 方法 是什么 输入 用户 数组 测试      更新时间:2023-10-16

我正在尝试编写一个用于玩强力球彩票的模拟器,该程序将要求5个数字(又名白球)并输入到6元素数组中,另一个数字(红色强力球)输入到第6个元素中。 我需要弄清楚如何在前5个元素中测试重复项,但第6个元素不需要是唯一的。

我有一个我认为可以工作的循环,但它甚至没有执行并且相当混乱。

有没有更有效的方法来测试重复项,可能涉及布尔标志?

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语句,但实际结果是输入数字后什么也没发生。

"我基本上只需要它来提醒用户,如果他们已经输入 数组中的一个数字,并提供另一个cin >> pBallNums语句。

在这种情况下,只需使用std::set并使用它std::set::emplace方法将用户输入存储到集合中。

cppreference.com

template< class... Args >
std::pair<iterator,bool> emplace( Args&&... args );

std::set::emplace

返回一对,其中包含插入元素的迭代器,如果未发生插入,则返回已存在的元素,以及指示插入是否已发生的布尔值。真 表示插入,false 表示不插入

只需将此信息用于您的案例,然后再次循环以获取下一个用户输入。


下面是一个示例代码(查看实时):

#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

排序,然后检查相邻项目是否相等。

首先,尽量不要将实际需求与实现细节混为一谈。

[...]程序将要求5个数字(又名白球) 并输入到一个 6 元素数组和另一个数字(红色 强力球)进入第6元素。

您真正想要的是:从用户输入中获取的 5 个不同的数字。从您的代码中,我读到检查应该在每次输入后进行。我想阅读最后一个数字很好,所以让我们把它放在一边。

接下来,习惯标准库中的容器。它们的数量并不多,但你可以用它们做什么是数不清的。要在容器中包含不同的元素,您需要std::unsorted_setstd::set。 那么基本上你所需要的只是使用insert

#include <set>
#include <iostream>
int main()
{
std::set<int> numbers;
auto x = numbers.insert(1);
std::cout << "1 was not present before? : " << x.second << "n";
x = numbers.insert(1);
std::cout << "1 was not present before? : " << x.second << "n";
}

指纹:

1 was not present before? : 1
1 was not present before? : 0