【问题标题】:c++ struct declaration within a function [duplicate]函数中的c ++结构声明[重复]
【发布时间】:2014-02-01 22:25:21
【问题描述】:

这可能是一个愚蠢的问题,但我写了如下代码。

void someFunction() {
    struct sort_pred {
        inline bool operator()(const std::pair<int,double>  &left, const std::pair<int,double>  &right) const {
            return left.second < right.second;
        }
    };
    std::sort(regionAreas.begin(), regionAreas.end(), sort_pred());
}

但是,这并不能编译说,

///:1542: error: no matching function for call to 'sort(std::vector<std::pair<int, double> >::iterator, std::vector<std::pair<int, double> >::iterator, someFunction::sort_pred)'

如何在函数中使用结构体作为比较器? 或者,不可能吗?

【问题讨论】:

标签: c++ struct std comparator stl-algorithm


【解决方案1】:

这是使用包装器的一个很好的例子。即使我们将实现从sort_predstd::pair&lt;int, double&gt; 的转换,它也不会正常工作,因为std::pair&lt;int, double&gt; 没有operator()。所以存储包装器而不是std::pair&lt;int, double&gt; 会做得很好。

class sort_pred;
class wrapper
{
    public:
        //some conversion-stuff from std::pair<int, double> to wrapper
        //not really needed in this example
        wrapper(const std::pair<int, double>& p) : _p(p) {}

        //needed in operator wrapper() in sort_pred
        wrapper(const sort_pred *s) : _p()
        {
            //////
            //maybe you want access to private-members of
            //sort_pred in here, so just add friend class sort_pred
            //to the class, if this is the case.
            //////
            //Just let the magic happen
            //////
        }

        //for std::sort
        bool operator()(const wrapper &left, const wrapper &right)
        {
            return left._p.second < right._p.second;
        }

    private:
        std::pair<int, double> _p;
};

struct sort_pred {
    sort_pred(){}

    //This allows us to static_cast sort_pred to wrapper
    operator wrapper()
    {
        return wrapper(this);
    }
};

bar foo()
{    
    std::vector<wrapper> regionAreas;
    //some stuff with regionAreas.push_back :D

    std::sort(regionAreas.begin(), regionAreas.end(), static_cast<wrapper>(sort_pred()));

   return bar_value;
}

【讨论】:

    【解决方案2】:

    您的问题似乎与Using local classes with STL algorithms 重复。

    简而言之,这在 C++11 中是允许的,但以前版本的 C++ 规范不允许这样做。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-11
      • 1970-01-01
      • 2016-05-09
      • 1970-01-01
      • 1970-01-01
      • 2010-11-08
      • 2018-05-13
      相关资源
      最近更新 更多