2015-12-13 22 views
0

問題結構的數組的元素:最小值和索引從在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 []最小值和位置費用?有可能使用std :: min_element找到它?

回答

2

我能想到的至少在四個方面與std::min_element

1做到這一點),添加一個 「小於」 的成員函數的struct /類:

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) 
+0

感謝您給予的答案這種記錄良好的方式。這給了我一種感覺,我對C++ –

+0

稍微複雜一點都不瞭解:如果我需要查找**所有**索引與最小值匹配,該怎麼辦? –

+0

@ Mr.EU:最簡單的方法可能就是使用for循環收集匹配最小值的索引。如果你在一次傳遞中做了這個,那麼可能像[ideone.com上的這段代碼](http://ideone.com/kE21eo) – Blastfurnace

3

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