[英]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;
}
}
我不知道該如何處理函數的類型,也許返回值也錯了。
您想要return max;
的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
很重要, v.size
您將嘗試訪問不存在的元素。 如果您的代碼沒有返回分段錯誤,那是因為std::vector
是安全的訪問。 這意味着std::vector
嘗試訪問該元素,但是無論如何,您正在執行最后一次不必要的迭代。 這就是為什么最好使用迭代器。
@KarthikT說的也很正確:您嘗試在每次迭代中返回max
,因此,在第一次迭代之后,函數將返回值並停止執行,請始終檢索向量的第一個值(如果該值大於0) )。
希望對您有所幫助。
不確定我是否正確地捕捉了您的主要問題。 您想將float to struct S
的max_search函數的返回值轉換float to struct S
嗎? 我將對KarithikT的答案進行按摩,並添加更多詳細信息:
要啟用implicit conversion
(從float到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從容器中查找max元素:
vector<float> v(10);
for (int i=0;i<10;i++) {
v[i]=sin(i);
}
S mx = *std::max_element(v.begin(), v.end());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.