使用结构定义函数
defining function using a struct
我是编程的新手,尤其是对C 。我有一个任务,其部分是使用结构编写功能。
struct S {
float m; //how many
int h; //where
float mx;
};
int main() {
S s;
s.m=0.5;
s.h=1;
vector<float> v(10);
for (int i=0;i<10;i++)
v[i]=sin(i);
S mx = max_search(v);
如果(mx.m>0.98935 && mx.m<0.9894 && mx.h==8
)。
我提出了此功能守则,但我知道,这是非常有缺陷的。
float max_search(vector<float> v) {
int max=0;
for (int i=0; i<v.size(); i++) {
if (v[i]>max) {
max=v[i];
}
return max;
}
}
我不知道,我该如何处理功能类型,也许是错误的返回值。
不确定我是否正确捕获了您的主要问题。您要转换 float to struct S
的max_search函数的返回值吗?我将按摩Karithikt的答案,并添加更多详细信息:
启用implicit conversion
(从浮点到struct S),需要将转换功能添加到S
struct S {
S():m(0.0), h(0), mx(0.0){ } //
S(float x):m(0.0), h(0), mx(x){ } // to enalbe convert float to S
float m; //how many
int h; //where
float mx;
};
float max_search(const vector<float>& v) { // pass by const reference
float max=0.0f;
for (int i=0; i<v.size(); i++) {
if (v[i]>max) {
max=v[i];
}
}
return max;
}
您也可以使用std :: max_element从容器中找到最大元素:
vector<float> v(10);
for (int i=0;i<10;i++) {
v[i]=sin(i);
}
S mx = *std::max_element(v.begin(), v.end());
您希望您的return max;
在最外部。现在,它返回for循环的每一个迭代,这意味着您只能获得1个迭代。
float max_search(vector<float> v) {
float max=0.0f; <------------
for (int i=0; i<v.size(); i++) {
if (v[i]>max) {
max=v[i];
}
--------------
}
return max; <------------
}
我想你想像这个 s.mx = max_search(v);
您也可以使用std::max_element
s.mx = std::max_element(v.begin(),v.end()); // (begin(v),end(v)) in c++11
如果将函数声明为 float
,为什么要返回 int
?
float max_search(vector<float> v) {
float max = v[0]; //this way you avoid an iteration
for (int i = 1; i < v.size() - 1; i++)
if (v[i] > max) max = v[i];
return max;
}
您也可以使用迭代器来执行此操作:
float max_search(vector<float> v) {
float max = .0;
for (vector<float>::iterator it = v.begin(); it != v.end(); ++it)
if (*it > max) max = *it;
return max;
}
在第一个代码块中,重要的是将1提取到v.size
,其他方式,您将尝试访问不存在的元素。如果您的代码没有返回您的细分故障,那是因为std::vector
是安全的。这意味着std::vector
尝试访问元素,但是无论如何,您正在执行最后一次内在迭代。这就是为什么最好使用迭代器。
@karthikt所说的也是正确的:您正在尝试在每次迭代中返回max
,因此,在第一次迭代后,函数返回值并停止执行,请始终检索向量的第一个值(如果此值是大于0)。
我希望这有所帮助。
相关文章:
- 不同翻译单元中不可重载的非内联函数定义
- Visual Studio中的函数声明和函数定义问题
- 编写代码时C++出现错误:错误 1 错误 C2601:'circle':本地函数定义是非法的
- 具有enable_if外部类原型的模板类构造函数定义
- 类的前向声明之后的类成员函数定义,在类声明之前
- 为函数定义符号不明确的指针参数
- C++模板专用化 - 无法匹配函数定义
- 错误:在第 6 行'{'标记之前,此处不允许使用函数定义
- 找不到 #define 的函数定义
- 根据类型特征更改函数定义?
- 将抽象基类中的所有纯虚函数定义为 varaidaic 模板
- 命名空间更改函数定义
- "Type&"与C++函数定义中的"Type*"
- C++:为什么允许在另一个函数中声明函数,而不允许在函数定义中声明?
- 如何从 C++ 中的现有模板函数定义新函数
- 私有在函数定义/实现的返回值范围内是什么意思 (c++)?
- 越界成员函数定义是否需要一个完全限定的类名,直到全局范围
- 为什么c++允许成员函数定义中实例的私有成员访问
- Qt基类函数定义
- C++函数定义中参数列表后面额外一对括号的含义