gpt4 book ai didi

c++ - 如何在不在 C++ 中有效使用容器的情况下打印 5 个值的最大索引?

转载 作者:太空宇宙 更新时间:2023-11-04 15:00:16 24 4
gpt4 key购买 nike

这 5 个值的索引以 1 开头,我的任务是打印具有最大值的索引。我试过下面的代码:

#include <iostream>
using namespace std;

int main()
{
int a, b, c, d, e;
cin >> a >> b >> c >> d >> e;
int cnt = 1;
if (a < b){
a = b;
cnt++;
}
if (a < c){
a = c;
cnt++;
}
if (a < d){
a = d;
cnt++;
}
if (a < e){
a = e;
cnt++;
}
cout << cnt;

}

是否有任何方法可以将我的代码简化为更少的行,或者更有效的方法,假设所有值都 >= 0

最佳答案

这是一个不使用容器的建议解决方案,仅使用 STL 算法和迭代器魔法。它也适用于输入的任意数量的数字,而不仅仅是 5 个。

#include <algorithm>
#include <iterator>
#include <iostream>
#include <climits>

int main()
{
int maxv = std::numeric_limits<int>::min();
int high_index;
int curIndex = 1;
std::for_each(std::istream_iterator<int>{std::cin},
std::istream_iterator<int>{}, [&](int n)
{
if (maxv < n)
{
high_index = curIndex;
maxv = n;
}
++curIndex;
});
std::cout << "Highest index: " << high_index;
}

Live Example

关于c++ - 如何在不在 C++ 中有效使用容器的情况下打印 5 个值的最大索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49952792/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com