查找向量中最小+最大值元素的函数
C++ Function to find the min+max value element in a vector
我刚开始学习c++,所以我对这个很陌生。
我有一个存储在主类中的向量vector<int> pricelist{30,10,16,25,13};
。
我想实现一个函数lowestNHighestPrices()
来返回一个Prices
对象,该对象为我提供了向量中最高和最低值的索引值(分别为0和1)。
class Prices {
protected:
int lowestPrice;
int highestPrice;
public:
Prices(const int lowestPriceIn, const int highestPriceIn)
: lowestPrice(lowestPriceIn), highestPrice(highestPriceIn) {
}
int getlowestPrice() const {
return lowestPrice;
}
int gethighestPrice() const {
return highestPrice;
}
};
方法将由以下代码行调用Prices prices = lowestNHighestPrices(prices);
我不完全确定语法,是否有某种类型的关键字,我可以使用getter方法,以便我可以从矢量获得最高和最低的值?使得getLowestPrice() == 0
和getHighestPrice() == 1
?
根据注释中的建议,您可以使用std::min_element
和std::max_element
。下面的代码(更新了空列表的Prices
类)使列表迭代一次。
class Prices {
protected:
int lowestPrice;
int highestPrice;
bool isValid;
public:
Prices() : lowestPrice(), highestPrice(), isValid(false) {}
Prices(const int lowestPriceIn, const int highestPriceIn)
: lowestPrice(lowestPriceIn), highestPrice(highestPriceIn) {}
void updateWith(int val)
{ if (!isValid) {
lowestPrice = highestPrice = val;
isValid = true;
}
else if (val < lowestPrice)
lowestPrice = val;
else if (val > highestPrice)
highestPrice = val;
}
};
Prices lowestNHighestPrices(const vector<int>& pricelist) {
Prices result;
for (auto val : pricelist)
result.updateWith(val);
return result;
}
如果您有c++ 11可用(您应该),只需使用std::minmax_element:
Prices lowestNHighestPrices(const vector<int>& pricelist)
{
assert( !pricelist.empty() ); // just in case
auto res = std::minmax_element(
pricelist.cbegin(),
pricelist.cend()
);
return Prices( *res.first, *res.second );
}
返回std::pair<int, int>
。
std::pair<int, int> lowestNHighestPrices() const
{
return {lowestPrice, highestPrice};
}
您的类已经有一个公共接口/方法来获取您的高和低价格值。从它返回另一个结构或使用引用传递参数虽然是一个可能的解决方案,但在这种情况下看起来毫无意义。在需要更泛型代码(如容器)的地方,应该优先使用另一个类/结构std::pair,因为它的命名是抽象的,可以访问成员变量。
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 使用指针从C++中的数组中获取最大值
- 如何将这个C++哈希表转换为动态扩展和收缩,而不是使用硬设置的最大值
- 如何创建一个函数来计算并返回平均值、最大值和最小值
- 在二维数组中查找最小值和最大值?
- 整数溢出,最大值为 pow(10,19)
- 以C++递归方式查找向量中的最大值
- C++ - 如何在结构向量中找到结构体一个成员的最大值?
- 查找数组中第一个最小值和最后一个最大值元素之间的算术平均值
- C++ 函数,用于查找传入的 N 个数字的平均值、总和、最小值和最大值
- 查找包含 N 个元素的数组的最小值和最大值
- 如何在 c++ 中创建对的优先级队列.这会弹出具有最小值的元素.默认的弹出最大值
- 查找元组元素 C++ 的最大值
- c if-statement的最大值在数组中的最大值未指向正确的元素
- 查找容器中高于阈值的最大值和最小值元素
- 函数,它接受三个参数:指向双数组的指针、指向最小值的指针和指向最大值元素的指针
- std::bitset中的元素数量是否有最大值
- 二进制搜索,用于查找排序数组中比给定值最小和最大的元素
- 查找向量中最小+最大值元素的函数
- 元素最大值和特征值中的正部分