首页 > 解决方案 > 打印特定范围内的数组

问题描述

我正在编写一个程序,它说:从键盘上读入 20 个数字,每个数字必须在 10 到 100 之间。如果用户输入了超出预期范围的任何数字,您必须反复要求一个新值,直到它可以接受为止。在读取每个数字时,仅当它不与已读取的数字重复时才打印它。请注意,只要在适当的范围内,相同的数字可以输入 20 次。但是,如果发生这种情况,则该数字将仅打印一次,因为其他数字是重复的。如果输入了许多本身(当然在范围内),我遇到的问题是只打印一次数字。这是我到目前为止所拥有的:

包括

int main()
{
    int SIZE{20};
    int myArray[SIZE]{0};

    for(int i{0}; i < SIZE; ++i)
    {
        while((myArray[i] < 10) || (myArray[i] > 100))
        {
            std::cout << "Enter a number: ";
            std::cin >> myArray[i];

            if(myArray[i] == myArray[i - 1])
            {
                std::cout << "Enter a number: ";
                std::cin >> myArray[i];
            }
        }
    }

    for(int i{0}; i < SIZE; ++i)
        std::cout << myArray[i] << " ";

    return 0;
}

标签: c++c++14

解决方案


一种方法是使用数组的所有值创建一个集合,然后仅打印该集合的值。该std::set对象将只为每个值保留一个唯一实例,因为它被设计为这样做。

#include <cstdio>
#include <string>
#include <iostream>
#include <set>

int main() {

  int SIZE{20};
  int myArray[SIZE]{0};

  for(int i{0}; i < SIZE; ++i)
  {
      while((myArray[i] < 10) || (myArray[i] > 100))
      {
          std::cout << "Enter a number: ";
          std::cin >> myArray[i];

          if(myArray[i] == myArray[i - 1])
          {
              std::cout << "Enter a number: ";
              std::cin >> myArray[i];
          }
      }
  }

  // Set declaration
  std::set<int> uniqueValues;
  for(int i{0}; i < SIZE; ++i)
      uniqueValues.insert(myArray[i]);

  // Printing set values
  for(auto itr = uniqueValues.begin(); itr != uniqueValues.end(); ++itr)
      std::cout << *itr << " ";

  return 0;
}

推荐阅读