我刚开始学习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,因为它的命名是抽象的,可以访问成员变量。