在对象数组中搜索字符串并返回相应值的函数

Function that searches object array for string and returns corresponding value

本文关键字:返回 函数 串并 字符串 数组 对象 搜索 字符      更新时间:2023-10-16

我需要创建一个函数,该函数获取输入的日期,并在高/低温数据集中搜索匹配的日期,然后返回该日期的相应最低温度。输入的日期格式与数组中的格式匹配,因此这不是问题。目前,该函数每次都返回 0。如果我不得不猜测,我认为 if 语句或我的 getDate 函数有问题。

double findLow(const char* date, const Weather *data, int dataSize) {
for (int i = 0; i < dataSize; i++) {
// If date matches, return lowest temp
if (date == data[i].getDate()) {
return data[i].getLow();
}   
}
return 0.0;
}

以下是我的其他功能:

const char* Weather::getDate() const {
return &date[0];
}
double Weather::getLow() const {
return lowTemp;
}

提前谢谢。

date == data[i].getDate()

你不能以这种方式比较指针。如果你无论如何都必须使用数组,最好使用 std::string(大多数日期表示应该使用专用类(。

改用std::string而不是const char*,否则只比较指针而不比较字符串内容。

class Weather
{
// ...
private:
std::string date;
public:
const std::string& getDate() const { return date; }
};