【问题标题】:How to get top 3 values from a vector smaller than a particular value?如何从小于特定值的向量中获取前 3 个值?
【发布时间】:2021-01-04 23:41:26
【问题描述】:

我有一个向量 {42.195 42.195 39.025 40.075 34.220 42.195 39.750}。在这里,我想获得仅小于 42.195 的前 3 个值。以下是我的方法。

  1. 我按降序对向量进行了排序。
  2. 初始化一个输出向量和一个计数器=0。
  3. 然后我遍历向量并检查元素是否不等于到 42.195。如果是这样,请增加计数器。如果计数器值

上述方法在逻辑上看起来不错,但是在将每个元素与 42.195 值进行比较时,代码无法正常工作。请帮帮我。

#include<bits/stdc++.h>
#include<vector>

using namespace std;

int validateData(vector<float> &arr){
    for(int i = 0 ; i < arr.size() ; i++){
        if(arr[i] <= 0.0){
            cout<<"\nInvalid data";
            return -1; 
        }
    }
    return 0;
}

vector <float> getTop3(vector<float>& arr){
    if(validateData(arr) == -1)
        cout<<"\nCannot perform operation";
    else {
        vector<float> output;
        int count = 0;
        cout<<"Sorted values are: \n";
        sort(arr.begin(), arr.end(), greater<float>());
        for(int i = 0 ; i < arr.size() ; i++){
            cout<<arr[i]<<" ";
        }
        for(int i = 0 ; i < arr.size() ; i++){
            if(arr[i] != 42.195) {
                count++;
                if(count <= 3)
                    output.push_back(arr[i]);
                else
                    break;
            }
        }
        cout<<"\nOutput vector is\n";
        for(int i = 0 ; i < output.size() ; i++){
            cout<<output[i]<<" ";
        }
        return output;
    }
}

int main(int argc, char *argv[]){
    vector<float> arr;
    cout<<"Arguments are:\n";
    for(int i = 1 ; i < argc ; i++){
        arr.push_back(stof(argv[i]));
    }
    for(int i = 0 ; i < arr.size() ; i++){
        cout<<arr[i]<<" ";
    }
    
    cout<<"\n";
    //Function call
    getTop3(arr);
}

下面是输出。

【问题讨论】:

  • 听起来您可能需要学习如何使用调试器来单步调试您的代码。使用好的调试器,您可以逐行执行您的程序,并查看它与您期望的偏差在哪里。如果您要进行任何编程,这是必不可少的工具。进一步阅读:How to debug small programsDebugging Guide
  • 另外,如果你正在对数据进行排序,你可以使用std::lower_bound,这会让问题变得更容易。
  • 'if(arr[i] != 42.195)' 由于浮点舍入,这可能会导致问题。您可以更改为 'if ( fabs(arr[i] - 42.195) > 1.0e-7)' 设置两个浮点数相等的容差。

标签: c++ vector


【解决方案1】:

std::partition 后跟 std::nth_element 可以完成这项工作:

std::vector<float> get_top3(std::vector<float> v, float threshold)
{
    auto end = std::partition(v.begin(), v.end(), [&](auto f){ return f < threshold; });
    if (std::distance(v.begin(), end) <= 3) return {v.begin(), end};
    std::nth_element(v.begin(), v.begin() + 3, end, std::greater<>{});
    return {v.begin(), v.begin() + 3};
}

int main() {
    std::vector<float> arr = {42.195, 42.195, 39.025, 40.075, 34.220, 42.195, 39.750};
    
    for (auto f : get_top3(arr, 42.195))
        std::cout <<  f << " ";
}

Demo

您的一个问题是:42.195 != 42.195f

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-14
    • 1970-01-01
    相关资源
    最近更新 更多