c++ - 非标准语法;使用 '&' 创建指向成员 C++ 的指针
问题描述
我在运行我的一小段代码时遇到问题。我有一个从用户输入读取温度的向量。我想稍微处理一下数据。给出这是哪一天(炎热的一天,夏天的一天,等等......),哪一天是最热的。但是每次我想用函数 maxNumber 获得最高温度时,我都会得到 2 个我不明白的错误:
non-standard syntax; use '&' to create a pointer to member
"! =": Function overload cannot be resolved
请帮忙!非常感谢
代码:
#include <iostream>
#include <vector>
std::string klimaTag(float a) {
if (a >= 25 and a < 30) {
return "Sommertag";
}
else if (a >= 30 and a < 35) {
return "Heißer Tag";
}
else if (a >= 35) {
return "Wüstentag";
}
else {
return "Normaltag";
}
}
float maxNumber(std::vector<float> &a) {
float current_max = 0;
for (int i = a.begin; i != a.end; i++) {
if (a.at(i) > current_max) {
current_max = a.at(i);
}
return current_max;
}
}
int main()
{
std::vector<float> temperatures;
float current_temp;
for (int i = 0; i < 5; i++) {
std::cout << "Hoechsttemp für Tag " << i << " eingeben: ";
std::cin >> current_temp;
temperatures.push_back(current_temp);
}
for (int i = 0; i < 5; i++) {
std::cout << "Tag " << i + 1 << " ist ein " << klimaTag(temperatures.at(i)) << std::endl;
}
std::cout << maxNumber(temperatures);
}
解决方案
首先begin()
and end()
are 方法,所以你得到这个错误是因为你试图引用一个函数,所以它应该需要一个地址运算符。
其次是返回一个begin()
而不是一个索引,并且您正在清除尝试访问类似的索引。end()
iterator
第三件事是你总是在第一个周期之后返回,因为你的返回在里面并且应该在外面。
要正确循环,您的数组足以使用 for range 循环
float maxNumber(std::vector<float> &a) {
float current_max = 0;
for(const auto& element : a) {
if(element > current_max){
current_max = element;
}
}
return current_max;
}
如果您想使用旧方式,您可以随时使用
float maxNumber(std::vector<float> &a) {
float current_max = 0;
for(int i=0; i<a.size(); ++a) {
if(a.at(i) > current_max){
current_max = a.at(i);
}
}
return current_max;
}
推荐阅读
- python - 二十一点游戏多轮系统
- c# - 我的 ASP.NET 3 Core MVC 上的浏览器链接问题
- vue.js - 带有参数和计算属性的 Vuex getter
- java - 在 Spring Data JPA 中,如何通过调用外部实体实例上的方法来创建和持久化内部实体
- list - 将 MFCC 与视频帧匹配
- mysql - 在 MySQL 和 go-sql-driver/mysql 之间更新了不一致的行
- c - 如何使用命令行输入文件在 linux 上运行 C 代码?
- windows - 在命令提示符 (cmd.exe) 中运行 psm1 PowerShell 脚本?
- sequelize.js - sequelize belongsToMany 将值添加到联结表
- python - 尝试将变量作为参数传递