关于算法:基于最大值索引C从2个向量中提取值

Extracting values from 2 vectors based on the max value index C++

我是一个新手程序员,试图习惯于使用向量。在下面的代码中,我能够找到向量" V"的最大值并将其返回给main。取而代之的是,我需要从另一个与最大值索引相对应的向量中返回该值。在这种情况下,向量" V"的最大值为65.25,我希望函数从向量" freq"(相同的索引)返回0.05。这些值来自以前使用矩阵进行的计算,并使用push_back方法将结果添加到矢量中,我只需要提取0.05即可进行进一步的操作。非常感谢您的帮助。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#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;
}


无需发明自己的搜索最大值的函数。您可以使用标准功能。

您在这里。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <vector>
#include <iterator>
#include

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 ) )
              << '\
'
;

    return 0;
}

程序输出为

1
65.25 -> 0.05

如果要使用您的函数,则应按照以下演示程序中所示的以下方式进行更改。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#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]
              << '\
'
;

    return 0;
}

程序输出与上面显示的相同

1
65.25 -> 0.05

您可以这样做:

1
2
3
4
5
6
7
8
9
10
11
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;
}

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