簡體   English   中英

獲取擁有最小值的struct數組的索引

[英]Get index of the struct array which holds the smallest value

編輯:我非常感謝答案!

因此,假設我們有一個這樣的結構

struct BadQuestion
{
   float a;
   float b;

} BadArray[10];

在典型的一天中, float a將如下所示

{ 0, 152.52, 25.26, 5.166, 263.25, 256.256, 452.25, 0, 0, 0 }

現在,我需要找到最小值(5.166)並獲取該值在數組中的索引(該值為3),因為稍后我需要從BadArray[3]提取float b

我當然不想在搜索中包括0值。 我已經累的是將所有非零值添加到向量中,然后使用min_element獲得float a的最低值。 問題是我不知道如何獲取索引。

當前代碼

vector<float> temp;
int size = 0;
for (int i = 0; i < 10; i++)
{
    if (BadArray[i].a != 0) {
        temp.push_back(BadArray[i].a);
        size++;
    }
}

auto entity = min_element(temp.begin(), temp.end());
float lowestvalue = FLT_MAX; //float max
int index = -1;
for(int i = 0; i < 10; i++)
{
     if(BadQuestion[i].a < lowestvalue && BadQuestion[i].a != 0)
     {
         lowestvalue = BadQuestion[i].a;
         index = i;
     }
}

float patato = BadQuestion[index].b;

因此,請使用自定義比較器! 這是一個相當長的:

#include <array>
#include <iostream>

int main() {
    std::array<float, 10> arr = {0, 152.52, 25.26, 5.166, 263.25, 256.256, 452.25, 0, 0, 0};

    auto it = std::min_element(begin(arr), end(arr), [](float lhs, float rhs) -> bool {
        if (lhs == rhs)
            return false;
        if (lhs == 0)
            return false;
        if (rhs == 0)
            return true;
        return lhs < rhs;
    });

    std::cout << std::distance(begin(arr), it) << "\n";
}

輸出:

3

我們也可以在BadQuestion上執行此工作:

struct BadQuestion {
    float a;
    float b;
};

int main() {
    std::array<struct BadQuestion, 3> arr;

    arr[0] = {12, 3};
    arr[1] = {0, 17};
    arr[2] = {9, 14};

    auto it = std::min_element(begin(arr), end(arr), [](BadQuestion const & lhs, BadQuestion const & rhs) -> bool {
        if (lhs.a == rhs.a)
            return false;
        if (lhs.a == 0)
            return false;
        if (rhs.a == 0)
            return true;
        return lhs.a < rhs.a;
    });

    std::cout << std::distance(begin(arr), it) << "\n";
    std::cout << it->b << "\n";
}

我不確定我是否完全理解您的問題,但是這里

#include <limits>
float min = numeric_limits<float>::max();
int minIndex = 0;
for (int i = 0; i < (sizeof(BadArray) / sizeof(BadArray[0])); i++) {
    if ((BadArray[i].a > 0) && (BadArray[i].a < min)) {
        min = BadArray[i].a;
        minIndex = i;
    }
}

這是一種有趣的方式,與其他示例完全不同:讓我們使用Boost.Ranges

float arr[] = { 0, 152.52, 25.26, 5.166, 263.25, 256.256, 452.25, 0, 0, 0 };

auto it = boost::min_element(
    arr | boost::adaptors::filtered(non_zero{}));

帶有:

struct non_zero {
    bool operator()(float f) { return f != 0.0; }
};

此時, *it == 5.166(&*it - arr) == 3是您的索引。 如果您希望min_element可以在您的結構上使用它,它還會使用一個比較器,因此您的non_zero也必須進行更改以考慮到這一點,但是結構看起來是相同的:基本上,這使我們可以將min_element部分與filtered部分分開,很好

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM