[英]Extracting values from 2 vectors based on the max value index C++
我是一個新手程序員,試圖習慣使用向量。 在下面的代碼中,我能夠找到向量“V”的最大值並將其返回到 main。 而不是我需要從對應於最大值索引的另一個向量返回值。 在這種情況下,向量“V”最大值為 65.25,我希望函數從向量“freq”(相同索引)返回 0.05。 這些值來自之前使用矩陣的計算,使用 push_back 方法將結果添加到向量中,我只需要提取 0.05 以進行進一步操作。 非常感謝幫助。
#include <iostream>
#include <vector>
#include <cmath>
#include <cfloat>
using namespace std;
double maxAt(vector<double> &Lvec); // MaxL value func prototype
int main() {
vector <double> freq = {0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07};
vector <double> V ={0, 0, 0, 0, 65.25, 0,6};
double MaxV = maxAt(V);
cout << MaxV << endl;
return 0;
}
double maxAt(vector<double> &V) {
double Lmax = DBL_MIN;
for (auto val : V) {
if (Lmax < val) Lmax = val;
}
return Lmax;
}
沒有必要發明自己的搜索最大值的函數。 您可以使用標准功能。
這個給你。
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
int main()
{
std::vector<double> freq = { 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07 };
std::vector<double> V = { 0, 0, 0, 0, 65.25, 0,6 };
auto it = std::max_element( std::begin( V ), std::end( V ) );
std::cout << *it << " -> "
<< *std::next( std::begin( freq ), std::distance( std::begin( V ), it ) )
<< '\n';
return 0;
}
程序輸出是
65.25 -> 0.05
如果要使用您的功能,那么您應該按照以下方式更改它,如下面的演示程序所示。
#include <iostream>
#include <vector>
auto maxAt( const std::vector<double> &V )
{
std::vector<double>::size_type max = 0;
for ( std::vector<double>::size_type i = 1; i < v.size(); i++ )
{
if ( V[max] < V[i] ) max = i;
}
return max;
}
int main()
{
std::vector<double> freq = { 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07 };
std::vector<double> V = { 0, 0, 0, 0, 65.25, 0,6 };
auto pos = maxAt( V );
std::cout << V[pos] << " -> "
<< *freq[pos]
<< '\n';
return 0;
}
程序輸出與上圖相同
65.25 -> 0.05
你可以這樣做:
double maxAt(vector<double> &V, vector<double> &freq) {
double Lmax = DBL_MIN;
double Lfreq = DBL_MIN;
for (size_t i = 0; i < V.size(); ++i) {
if (Lmax < V[i]) {
Lmax = V[i];
Lfreq = freq[i];
}
}
return Lfreq;
}
另外,請參閱此處以獲取使用標准算法的答案: 查找最大元素的位置
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.