xingd.net

.net related techonology

导航

处理map遍历的binder类: depair

Posted on 2005-06-08 17:06  xingd  阅读(1798)  评论(2编辑  收藏  举报
因为STL库广泛使用了Iterator, functor, binder,因此可以写出一个能够融入STL库的Adapter类,提高代码的通用性。
比如STL算法中传入的functor型别要求为ReturnType& func(Type& elem),而map中同时存了key和value,有时候需要使用ReturnType& func(KeyType& key, ValueType& value)的回调,那就可以写这样一个functor
 
template<typename Operation>
class depair
    : public unary_function<
                 pair<
                      typename Operation::first_argument_type,
                      typename Operation::second_argument_type>,
                 typename Operatoin::result_type>
{
    public:
        typedef pair<
                     typename Operation::first_argument_type,
                     typename Operation::second_argument_type> argument_type;
        typedef typename Operation::result_type result_type;
       
        depair(const Operation& func) : op(func) { };
       
        result_type operator() (const argument_type& arg)
        {
            return op(arg.first, arg.second);          
        }
       
        result_type operator() (const argument_type& arg) const
        {
            return op(arg.first, arg.second);
        }
    protected:
        Operation op;       
};
 
有了depair后,就可以使用以下的代码
 
void traverse(const int& key, const string& value)
{
 
}
 
map<int, string> mymap;
 
std::for_each(mymap.begin(), mymap.end(), depair<std::ptr_fun(traverse)>());
 
并且depair可以和其他的binder一起使用,比如
void check(const int& key, const string& value, int check_value)
{
 
}
 
map<int, string> mymap;
 
std::for_each(mymap.begin(), mymap.end(), depair<boost::bind(check, _3, 100)>());
 
上面的一行代码中,首先用boost::bind将check的第三个参数绑定值100,也就是传给check方法的check_value值固定为100,然后再绑定到depair去处理map的遍历。