簡體   English   中英

C ++中結構數組元素的最小值和索引

[英]min value and index from elements of array of structure in C++

問題:

#include <iostream>
#include <algorithm>
using namespace std;

struct abc
{
   int cost;
   int any;
};

int main() {
abc *var1 = new abc[5];
   var1[0].cost = 4;
   var1[1].cost = 42;
   var1[2].cost = 5;
   var1[3].cost = 0;
   var1[4].cost = 12;

  //       cout<< "value = " << *std::min_element(var1.cost,var1.cost+5) << endl;
  //       cout << "Position = " << (std::min_element(var1.cost,var1.cost+5)-var1.cost) << endl;
    return 0;
}

如何找到var1 []。cost的最小值和位置? 可以使用std :: min_element找到它嗎?

std :: min_element-cppreference.com

您可以使用比較函數對象讓std::min_element查看成員cost

#include <iostream>
#include <algorithm>
using namespace std;

struct abc
{
   int cost;
   int any;
};

struct cmp_abc {
  bool operator()(const abc& a, const abc& b) const {
    return a.cost < b.cost;
  }
};

int main() {
   abc *var1 = new abc[5];
   var1[0].cost = 4;
   var1[1].cost = 42;
   var1[2].cost = 5;
   var1[3].cost = 0;
   var1[4].cost = 12;

   abc *res = std::min_element(var1, var1 + 5, cmp_abc());

   cout << "value = " << res->cost << endl;
   cout << "Position = " << (res - var1) << endl;

   delete[] var1;
   return 0;
}

我可以想到至少四種方法來使用std::min_element

1)向結構/類添加“小於”成員函數:

struct abc
{
    int cost;
    int any;

    bool operator<(const abc &other) const { // member function
        return cost < other.cost;
    }
};

int main() {
    // ...
    // The algorithm will find and use the class operator< by default
    abc *ptr = std::min_element(var1, var1 + 5);
}

2)定義一個自由函數:

bool abc_less(const abc &lhs, const abc &rhs) // free function
{
    return lhs.cost < rhs.cost;
}

int main() {
    // ...
    // Pass a function pointer to the algorithm
    abc *ptr = std::min_element(var1, var1 + 5, abc_less);
}

3)定義一個功能對象類型:

struct abc_less // function object
{
    bool operator()(const abc &lhs, const abc &rhs) const {
        return lhs.cost < rhs.cost;
    }
};

int main() {
    // ...
    // Construct and pass a function object to the algorithm    
    abc *ptr = std::min_element(var1, var1 + 5, abc_less());
}

4)創建一個lambda函數:

int main() {
    // ...
    // Create a lambda at the point of call in this example
    abc *ptr = std::min_element(var1, var1 + 5, [](const abc &lhs, const abc &rhs) { return lhs.cost < rhs.cost; });
}

最后,使用返回的迭代器(在這種情況下為指針)來打印值或偏移量:

std::cout << "Value = " << ptr->cost << '\n';
std::cout << "Position = " << (ptr - var1) << '\n'; // or std::distance(var1, ptr)

暫無
暫無

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

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