对于C ++ sort(),如何将参数传递给自定义比较函数? [英] For C++ sort(), how to pass a parameter to custom compare function?

查看:51
本文介绍了对于C ++ sort(),如何将参数传递给自定义比较函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用标准的排序功能对点相对于另一个点的距离(例如,其重心)进行排序.

I want to use the standard sort function for sorting points in respect to their distance of another point (e.g. their barycenter).

我知道我可以编写一个自定义的比较函数,但是我不知道如何将参数传递给它.我希望它具有线程安全性,因此我不想将参数存储在一个中央位置.有没有办法将其他参数传递给自定义比较函数?

I know I can write a custom compare function, but I don't know how to pass a parameter to it. I want to have it thread-safe, so I do not want to store the parameter at one central location. Is there a way how to pass additional parameters to a custom compare function?

// Here is a compare function without a parameter for sorting by the x-coordinate
struct Point2fByXComparator {
    bool operator ()(Point2f const& a, Point2f const& b) {
        return a.x > b.x;
    }
};

// Here is the outline of another comparator, which can be used to sort in respect
// to another point. But I don't know how to pass this other point to the compare
// function:
struct Point2fInRespectToOtherPointComparator {
    bool operator ()(Point2f const& a, Point2f const& b) {
        float distanceA = distance(a, barycenter);
        float distanceB = distance(b, barycenter);

        return distanceA > distanceB;
    }
};

std::vector<Point2f> vec = ...;

Point2f barycenter(0, 0);
for (int i = 0; i < vec.size(); i++) {
    barycenter += vec[i];
}
barycenter *= (1.0/vec.size());

// In the next line I would have to pass the barycenter to the compare function
// so that I can use the barycenter for comparison. But I don't know how to do
// this.
sort(vec.begin(), vec.end(), Point2fInRespectToOtherPointComparator());

推荐答案

请记住,结构和类几乎相同,请在该类中添加一个成员.

Remembering that a struct and a class are pretty much identical, add a member to the class.

struct Point2fBarycenterComparator {
    explicit Point2fBarycenterComparitor(Point2f barycenter_) 
    : barycenter(barycenter_) {}

    bool operator ()(Point2f const& a, Point2f const& b) const {
        float distanceA = distance(a, barycenter);
        float distanceB = distance(b, barycenter);

        return distanceA > distanceB;
    }

    Point2f barycenter;
};

std::vector<Point2f> vec = ...;
Point2f barycenter = ...;
sort(vec.begin(), vec.end(), Point2fBarycenterComparator(barycenter));

这篇关于对于C ++ sort(),如何将参数传递给自定义比较函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆