通常,您可以使用可用的functional函子来纯粹从标准构造中构造结果排序函子。
但是没有取消引用指针的方法T*,因此您必须使用自己的比较器。
您可以获得的最接近的是当您的“指针类型”不是原始类型,而是一些operator*可以解决的用户定义类型时。
以下代码是 C++11(使用std::bind起来比std::bind1stand更简单std::bind2nd)。
#include <vector>
#include <algorithm>
#include <functional>
#include <iostream>
// Fakes a "smart pointer" wrapper around data
template <typename T>
struct Ptr
{
Ptr(T data) : data(data) {};
const T& operator*() const { return data; }
private:
T data;
};
int main()
{
std::vector<Ptr<double>> vIn;
vIn.push_back(Ptr<double>(5));
vIn.push_back(Ptr<double>(2));
vIn.push_back(Ptr<double>(6));
using namespace std::placeholders;
std::sort(
vIn.begin(),
vIn.end(),
std::bind(
std::less<double>(),
std::bind(&Ptr<double>::operator*, _1),
std::bind(&Ptr<double>::operator*, _2)
)
);
std::vector<Ptr<double>>::const_iterator it = vIn.begin(), end = vIn.end();
for ( ; it != end; ++it)
std::cout << ',' << **it;
}
因此,如果不是double*你有std::unique_ptr<double>or std::shared_ptr<double>,那么这可以工作:
#include <vector>
#include <memory>
#include <algorithm>
#include <functional>
#include <iostream>
int main()
{
typedef std::unique_ptr<double> STDUPD;
std::vector<STDUPD> vIn;
vIn.push_back(STDUPD(new double(5)));
vIn.push_back(STDUPD(new double(2)));
vIn.push_back(STDUPD(new double(6)));
using namespace std::placeholders;
std::sort(
vIn.begin(),
vIn.end(),
std::bind(
std::less<double>(),
std::bind(&STDUPD::operator*, _1),
std::bind(&STDUPD::operator*, _2)
)
);
std::vector<STDUPD>::const_iterator it = vIn.begin(), end = vIn.end();
for ( ; it != end; ++it)
std::cout << ',' << **it;
}
如果可以的话,还有另一个避免“原始”指针的原因......