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;
    bool replace = True;
    for (y=0; y<x; y++)
       if (number != arr[y])
         cout << "try next time" << endl;
         replace = False;

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

标签: c++ arrays flags
2楼-- · 2019-10-07 03:47

Take a closer look at where you increment x.

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.

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;
  if (n == 5) break;
倾城 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;)
登录 后发表回答