c++ - 根据另一个 vector 对点 vector 进行排序

标签 c++ sorting c++11 vector stl-algorithm

我正在开发 C++ 应用程序。

我有 2 个点 vector

vector<Point2f> vectorAll;
vector<Point2f> vectorSpecial;  

Point2f 定义 typedef Point_<float> Point2f;

vectorAll 有 1000 个点,而 vectorSpecial 有 10 个点。

第一步:

我需要根据 vectorAll 中的顺序对 vectorSpecial 中的点进行排序。 所以像这样:

For each Point in vectorSpecial
    Get The Order Of that point in the vectorAll
    Insert it in the correct order in a new vector

我可以做一个双循环并保存索引。然后根据它们的索引对点进行排序。然而,当我们有很多点时(例如 vectorAll 中有 10000 个点,vectorSpecial 中有 1000 个点,所以这是一千万次迭代)

这样做的更好方法是什么?

第二步:

vectorSpecial 中的一些点在 vectorAll 中可能不可用。我需要取离它最近的点(通过使用通常的距离公式 sqrt((x1-x2)^2 + (y1-y2)^2) )

这也可以在循环时完成,但如果有人对更好的方法有任何建议,我将不胜感激。

非常感谢您的帮助

最佳答案

您可以在 vectorAll 上使用 std::sort 以及旨在考虑 vectorSpecial< 内容的 Compare 函数:

struct myCompareStruct
{
    std::vector<Point2f> all;
    std::vector<Point2f> special;
    myCompareStruct(const std::vector<Point2f>& a, const std::vector<Point2f>& s)
        : all(a), special(s) 
    {
    }
    bool operator() (const Point2f& i, const Point2f& j) 
    { 
        //whatever the logic is
    }
};

std::vector<Point2f> all;
std::vector<Point2f> special;
//fill your vectors
myCompareStruct compareObject(all,special);

std::sort(special.begin(),special.end(),compareObject);

关于c++ - 根据另一个 vector 对点 vector 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11341498/

相关文章:

c++ - GCC 使用哪种排序算法?

c++ - 模板参数列表中的部分模板推导

C++ 运算符 < 重载

javascript - 过滤不适用于 AngularJS 中的对象数组

c++ - 参数包函数参数可以默认吗?

c++ - 为什么 w/cout 不支持字符串 U/u 前缀?

c++ - 在同一全局内存位置并发写入

javascript - 在 Javascript 中对多维 JSON 对象进行排序

c++ - std::function operator() 和 std::forward 发生了什么?

c++字符串使用assign函数和直接使用 '='改变值的区别