如何禁止在2D数组上重复输入值?



这是我的代码,我想在用户试图输入相同的值时限制重复出现的值。如果一切都只在主函数中,那将是最好的,因为我还在学习如何声明更多的函数。

#include <iostream>
using namespace std;
int main() {

int num[10][10];
int times;

cout << "Please input the number of times you wish to enter a value but does not exceed to 100: ";
cin >> times; 

cout << "Enter a value " << times * times << " times." << endl;


for(int i = 0; i < times; i++) {
for(int k = 0; k < times; k++) {
cout << "Please input a number on index [" << i << "][" << k << "]: ";
cin >> num[i][k];
}
}

//Displaying the inputs
cout << "Printing all values inside the array: " << endl; 
for(int i = 0; i < times; i++) {
cout << endl;
for(int k = 0; k < times; k++) {
cout << "t" << num[i][k] << " ";     
}
}
return 0;        
}

当用户尝试输入重复值时,我期望的输出是:

请输入索引[0][0]:7的数字请在索引[0][1]:7上输入一个数字已输入的值。请再试一次。请输入索引[0][1]上的数字:

在这种情况下,您可以使用这样的函数:

bool doesExist(
const int array[][10], const size_t size, const int value, int x, int y)
{
for (size_t i = 0; i < size; i++)
for (size_t j = 0; j < size; j++) {
if (x == i && y == j)
continue; // Skip the new element.
// If duplicate found
if (value == array[i][j])
return true;
}
return false;
}

接受数组、数组大小、要比较的值以及第一次插入的唯一元素的位置作为参数。

你可以这样实现:

cin >> num[i][k];
if (doesExist(num, times, num[i][k], i, k)) {
cout << "Already exists.n";
...
}

这不是解决这个问题的最佳方法。在c++中,推荐使用STL容器,因为它们提供了更多的安全性和迭代器。

您只希望使用不输入重复的值:-

  1. 首先你可以检查所有之前的值,如果它与当前值匹配,那么你可以告诉用户更改值。

  2. 你可以使用unordered_map,因为map是(键,值)对,当你在map中插入任何值时,只需将其对应的值设置为1,然后你可以检查你的map中该值是否已经存在,如果它存在,那么你可以告诉用户更改,在map中它将很容易搜索。(代码很简单)

最新更新