gpt4 book ai didi

c++ - C++中结构数组元素的最小值和索引

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:17:57 30 4
gpt4 key购买 nike

问题:

#include <iostream>
#include <algorithm>
using namespace std;

struct abc
{
int cost;
int any;
};

int main() {
abc *var1 = new abc[5];
var1[0].cost = 4;
var1[1].cost = 42;
var1[2].cost = 5;
var1[3].cost = 0;
var1[4].cost = 12;

// cout<< "value = " << *std::min_element(var1.cost,var1.cost+5) << endl;
// cout << "Position = " << (std::min_element(var1.cost,var1.cost+5)-var1.cost) << endl;
return 0;
}

如何找到var1[].cost的最小值和位置?是否可以使用 std::min_element 找到它?

最佳答案

std::min_element - cppreference.com

您可以使用比较函数对象让 std::min_element 查看成员 cost

#include <iostream>
#include <algorithm>
using namespace std;

struct abc
{
int cost;
int any;
};

struct cmp_abc {
bool operator()(const abc& a, const abc& b) const {
return a.cost < b.cost;
}
};

int main() {
abc *var1 = new abc[5];
var1[0].cost = 4;
var1[1].cost = 42;
var1[2].cost = 5;
var1[3].cost = 0;
var1[4].cost = 12;

abc *res = std::min_element(var1, var1 + 5, cmp_abc());

cout << "value = " << res->cost << endl;
cout << "Position = " << (res - var1) << endl;

delete[] var1;
return 0;
}

关于c++ - C++中结构数组元素的最小值和索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34248336/

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