在对象数组中搜索字符串并返回相应值的函数
Function that searches object array for string and returns corresponding value
我需要创建一个函数,该函数获取输入的日期,并在高/低温数据集中搜索匹配的日期,然后返回该日期的相应最低温度。输入的日期格式与数组中的格式匹配,因此这不是问题。目前,该函数每次都返回 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; }
};
相关文章:
- 为什么将值返回函数传递给重载=运算符对运算符函数有效,而对其他运算符无效
- 编译器警告:执行到达值返回函数的末尾而不返回值
- 接收和返回函数指针的函数指针的类型?
- 我的动态链接队列在同一输出流中调用时不正确地输出三个返回函数
- C++函数链返回函数
- 返回函数指针的函数的签名
- 由于值返回函数中的错误,程序无法编译.它说未声明的标识符
- 非常量引用返回函数在常量值返回函数上用作 r 值
- 如何在 C++ 中从 void 返回函数访问变量
- 返回函数中带有 2 个可选 ctor 的对象
- 如何在 c++ 中返回函数的结构向量
- 返回 C++ 函数中的引用
- 使用向量时,当返回函数更改时,无法看到输出
- 如何在递归中使用返回函数
- 返回函数模板的类型C++作为第二个模板参数
- 为什么静态指针返回函数中有一个"静态"键?
- 递归返回函数,在特殊情况下不返回
- 从类返回函数
- 从类成员函数返回函数指针
- 从返回函数中推断不存在的模板参数