通常,您可以使用the functors available in functional
純粹由標準構造構造一個結果分類仿函數。
但是沒有一個可以取消引用T*
所以你必須使用你自己的比較器。
你可以得到的最接近的是當你的「指針」是不是原始的,但有些用戶定義型與operator*
可以得到解決。
以下代碼是C++ 11(使用std::bind
比std::bind1st
和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>
或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;
}
另一個原因,以避免「原始」的指針,如果你能......
爲什麼設置'而不是隻設置''? –
billz
有些情況下,在STL容器中有指向**的指針**。在C++中不應該有一個標準的解決方案,它不需要用戶製作的模板?有些情況下,[**指針指向指針指針**](http://www.c2.com/cgi/wiki?ThreeStarProgrammer)... – Praetorian
@billz這是一個簡單的例子,以減少問題最低。您可以通過指向堆上創建的某個胖對象的指針來替換double *。 – Raffi