【问题标题】:Extracting values from 2 vectors based on the max value index C++根据最大值索引 C++ 从 2 个向量中提取值
【发布时间】:2020-02-26 19:12:03
【问题描述】:

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

【问题讨论】:

  • 考虑创建一个结构,将最大值和与之相关的计算值绑定到一个对象中,然后拥有该结构的单个vector。当您找到最大值时,您也找到了匹配的计算值。

标签: c++ algorithm vector max


【解决方案1】:

没有必要发明自己的搜索最大值的函数。您可以使用标准功能。

你来了。

#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

【讨论】:

    【解决方案2】:

    你可以这样做:

    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;
    }
    

    另外,请参阅此处以获取使用标准算法的答案:Finding the position of the max element

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-09
      • 2021-06-16
      • 1970-01-01
      • 2014-12-28
      • 2019-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多