c – 小于函数的解引用指针
发布时间:2020-12-16 07:02:59 所属栏目:百科 来源:网络整理
导读:有些情况下,一个人在STL容器中有指针,而且不能通过指针而是通过指向的对象进行比较.一个简单的例子是一个矢量,它应该按实数排序.目前我解决这个问题: templateclass T_PTR struct ltDeref{ bool operator()(T_PTR p0,T_PTR p1) const {return *p0*p1;}}; 并
有些情况下,一个人在STL容器中有指针,而且不能通过指针而是通过指向的对象进行比较.一个简单的例子是一个矢量,它应该按实数排序.目前我解决这个问题:
template<class T_PTR> struct ltDeref { bool operator()(T_PTR p0,T_PTR p1) const {return *p0<*p1;} }; 并用它作为 vector<double*> vIn; sort(vIn.begin(),vIn.end(),ltDeref<double*>()); 要么 set<double*,ltDeref<double*> > someSet; 而不是编写我自己的比较函数,C中是否有更“标准”的方式,不需要用户制作模板? 解决方法
通常,您可以使用
the functors available in
functional 纯粹从标准构造构造结果排序仿函数.
但是没有一个可以取消引用指针T *,所以你必须使用你自己的比较器. 你可以得到的最接近的是你的“指针类型”不是一个原语,而是一些用户定义的类型,其中有一个可以被寻址的运算符*. 以下代码是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(),std::bind( std::less<double>(),std::bind(&Ptr<double>::operator*,_1),_2) ) ); std::vector<Ptr<double>>::const_iterator it = vIn.begin(),end = vIn.end(); for ( ; it != end; ++it) std::cout << ',' << **it; } > Output:,2,5,6 因此,如果不是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(),std::bind(&STDUPD::operator*,_2) ) ); std::vector<STDUPD>::const_iterator it = vIn.begin(),' << **it; } > Same output 如果可以的话,避免“原始”指针的又一个原因…… (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |