沒有多餘的代碼,讓我們看看下面的代碼示例:排序基於將吸氣構件功能的STL容器,以書面
// Example program
#include <iostream>
#include <string>
#include <algorithm>
class A
{
public:
A(const std::string& name) : name(name) {}
inline const std::string& getName() const { return name; }
private:
std::string name;
};
int main()
{
std::vector<A> v;
v.push_back(A("b"));
v.push_back(A("a"));
// want to sort the container, based on it's name!
}
我知道如何做到這一點(無論是定義一個內部或外部operator<
,或宣佈一個仿函數結構/類,它提供一個operator()
,並把它傳遞給std::sort
fonction),例如:
bool operator<(const A& a) const
{
return getName() < a.getName();
}
但是,我很懶有這個我想基於一個包含的類進行排序的容器都必須這樣做屬性,特別是當t他的課爲它提供了一個getter功能。
是否有可能基於類成員函數結果值請求排序(如果此函數顯然有比較器可用)?
喜歡的東西:
std::sort(v.begin(), v.end(), &(A::getName));
無需聲明一個新的運營商或仿函數?
可選問題:如果vector包含指針(std::vector<A*> v
)......如果單行語句可以根據A::getName
結果對它進行排序,那該怎麼辦?
範圍TS應該允許'的std ::排序(V,&A ::的getName);'。 – Jarod42
這將是偉大的....但它報告非法使用非靜態成員函數const string&A :: getName()const''(參見http://cpp.sh/7eqf) – jpo38
如果使用C++ 11或更大,你可以使用lambda:'std :: sort(v.begin(),v.end(),[](const A&a,const A&b){return a.getName()
Garf365