使用结构定义函数

defining function using a struct

本文关键字:函数 定义 结构      更新时间:2023-10-16

我是编程的新手,尤其是对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)。

我希望这有所帮助。