arrays and index [closed]

2019-10-07 03:18发布

How can I enter numbers into an array such that duplicate entries are ignored?

For example, if I put 6 and then 3 into the array, attempting to then insert 6 into the the array should cause 6 to be rejected (since it is already in the array).

#include <iostream>

using namespace std;
int main()
{
  int x,y;
  int number;
  int arr[5];

  for (x=0; x<5; )
  {
    cout<<"enter a number:"<<endl;
    cin>>number;
    bool replace = True;
    for (y=0; y<x; y++)
    {
       if (number != arr[y])
       {
         cout << "try next time" << endl;
         replace = False;
         break;
       }
    }

    if (replace)
    {
      arr[x] = number;
      x++;
    }
  }
  return 0;
}

标签: c++ arrays flags
9条回答
劳资没心,怎么记你
2楼-- · 2019-10-07 03:47

Take a closer look at where you increment x.

查看更多
Melony?
3楼-- · 2019-10-07 03:49

you have too many x++'s and you don't preset arr (maybe more style than error)

how do you know it's not working? (put some debug code inside of if (number == arr[y]) and if (replace)

查看更多
别忘想泡老子
4楼-- · 2019-10-07 03:51

You shouldn't use arrays for this. You should use, for example, std::set. Or, if you need to have an array as your data structure, you could encapsulate the array (e.g. realized through std::vector) in a class and define specific functions to access the array elements. Additionally, you could hold a std::set to provide a fast check for existing elements.

查看更多
Rolldiameter
5楼-- · 2019-10-07 03:52

It looks like you want to read in a sequence of numbers eliminating any duplicates. It also appears that the maximum number of unique numbers is 5.

int n = 0;  /* The number of unique numbers read in so far */
for {;;}
  cout << "enter nmber" << endl;
  cin >> number;
  for (x=0; x < n; ++x) {
    if (number == arr[x]) goto L1;  /* I love messing with peoples head by using this goto */
  }
  arr[n] = number;
  ++n;
  if (n == 5) break;
L1:
  continue;
}
查看更多
倾城 Initia
6楼-- · 2019-10-07 03:53

You don't want an array but a datastructure called Hashtable for that;

Alternatively, you might want to look up a datastructure called associative array.

查看更多
时光不老,我们不散
7楼-- · 2019-10-07 03:55

Take out the x++ in the for loop, That way you will only increment that count when you enter a new number.

Also, if you want to only run the loop five times, your outer for loop should be only to x<5.

All in all your outer loop should read:

for (x=0;x<5;)
查看更多
登录 后发表回答