我應該使用什么?bool compare 還是 sCompare() 函子?為什么?使用這兩個選項之間有什么區別嗎?
struct Dog
{
int m_age{};
int m_weigt{};
};
bool compare(const Dog& a, const Dog& b)
{
return a.m_age > b.m_age;
}
struct sCompare
{
bool operator()(const Dog& a, const Dog& b)
{
return a.m_age > b.m_age;
}
};
int main()
{
vector<Dog> dogs{ Dog{1,20}, Dog{2,10}, Dog{3,5}, Dog{10,40} };
//sort(begin(dogs), end(dogs), compare); this
//sort(begin(dogs), end(dogs), sCompare()); or this
return 0;
}
uj5u.com熱心網友回復:
您的兩個比較器導致相反的順序(<vs >)。除此之外最大的區別是你不能在函式中定義函式,但你可以在函式中定義型別。此外,lambda 運算式提供了簡單的語法來做到這一點:
int main()
{
vector<Dog> dogs{ Dog{1,20}, Dog{2,10}, Dog{3,5}, Dog{10,40} };
sort(begin(dogs), end(dogs), [](const Dog& a,const Dog& b){ return a.m_age < b.m_age;});
// or
auto comp = [](const Dog& a,const Dog& b){ return a.m_age < b.m_age;}
sort(begin(dogs), end(dogs),comp);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/327732.html
