c++ - 打印特定范围内的数组
问题描述
我正在编写一个程序,它说:从键盘上读入 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;
}
解决方案
一种方法是使用数组的所有值创建一个集合,然后仅打印该集合的值。该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;
}
推荐阅读
- node.js - 业务逻辑有效,但 Mongoose 保存无效
- caching - 什么是缓存驱动程序中的分布式原子锁?
- android - 当进度条显示它改变了我的界面设计
- mongodb - 由于更新弃用警告,如何在 updateMany 中实现推送?
- netcdf - 有没有办法使用 Web 界面在 shapefile 上显示 grib2 或 netcdf 数据?
- c# - Mysql EF6 C#中如何根据存储过程生成复杂类型
- javascript - 如何从 Object3D 创建 BufferGeometry?
- javascript - ie11中setMaxDate(new Date(today))的函数
- python - pydicom 数据集:send_c_find 返回成功,但 status.pixel_array 中有错误文本
- mysql - 选择具有相同 id 但在另一列中的所有空值的行并按相同 id 分组