我正在使用 C++ 程序将随机值存储在大小为 1000 的数组中。然后程序将要求用户输入“X”最大和“Y”最小数字。'X' 和 'Y' 是任何小于数组大小的整数值。然后程序将从数组中输出“X”最大和“Y”最小的数字。
假设数组有 1 2 4 7 9 14 3
X=2
Y = 3
输出将是
数组中最大的 2 个数字是 14 9
数组中最小的 3 数是 1 2 3
#include<iostream>
using namespace std;
int main()
{
int size[1000];
int x, y, max;
max = 0;
cout << "How many Largest numbers do you need ?\n";
cin >> x;
cout << "How many Smallest numbers do you need ?\n";
cin >> y;
for (int i = 0;i <= 999;i++)
{
size[i] = rand() % 100;
cout << "No." << i << " = " << size[i] << endl;
}
for (int j = 1;j <= x;j++)
{
for (int i = 0;i <= 999;i++)
{
if (size[i] > max)
max = size[i];
}
cout << "LARGEST NUMBERS\n" << max << endl;
}
}
这是使用std::set的解决方案。由于 astd::set
已经对其条目进行了排序,plus 不存储重复项,因此解决方案变得非常简单:
#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <set>
int main()
{
int size[1000];
int x, y;
std::cout << "How many Largest numbers do you need ?\n";
std::cin >> x;
std::cout << "How many Smallest numbers do you need ?\n";
std::cin >> y;
srand(0); // seed random number
// generate the numbers in the array
std::generate(size, size + 1000, []{return rand() % 1000;});
// create a std::set consisting of the numbers in the array
std::set<int> intSet(size, size + 1000);
该std::generate
函数自动“循环”并用随机值填充数组。
该std::set<int>
构造简单地创建一个std::set
阵列中使用的值。请注意,这将自动排序并删除重复条目。
一旦你有了这个,那么只需打印出 .csv 文件中的第一个x
数字和最后一个y
数字std::set
。
// print the smallest numbers
auto iter1 = intSet.begin(); // beginning of the set
int i = 0;
while (i < y)
{
std::cout << *iter1 << " ";
++iter1;
++i;
}
std::cout << "\n";
// print the largest numbers
auto iter2 = intSet.rbegin(); // end of the set. We will loop backwards
i = 0;
while (i < x)
{
std::cout << *iter2 << " ";
++iter2;
++i;
}
}
最大的数字从集合的末尾开始向后打印,这就是使用反向迭代器的原因。
注意:您必须在打印出值的循环中进行检查,以确保迭代器不会落在集合的开头和结尾。我把它留给你作为练习。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句