基于最大值索引C++从2个向量中提取值



我是一个新手程序员,试图习惯使用向量。在下面的代码中,我能够找到向量"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;
}

此外,请参阅此处获取使用标准算法的答案:查找最大元素的位置

最新更新