【问题标题】:Sorting Coordinate Points c++排序坐标点c ++
【发布时间】:2011-11-05 03:50:08
【问题描述】:

在一个应用程序中,我测量了很多二维坐标 (x,y) 图案。该模式由网格上的一组点组成,固定 x 和 y 方向的间距。这些坐标都有一个分数 质量并按此分数排序。我想做的是排序 这些坐标首先在 x 上定义组(区域) 属于一起的 x 坐标。在这一步之后,我想对 y 区域中的不同 x 区域。

在此之后,我可以将坐标标记为相应的 图案(网格)标签。

示例:测量坐标 (x,y)= (2,2),(2,3),(1,2),(1,3),(2,1),(1,1),(3,2),(3 ,3),(3 ,1)

在第 1 步之后: (x,y)= (1,2),(1,3),(1,1) (2,2),(2,3),(2,1) (3,2),(3,3 ),(3,1)

在第 2 步之后: (x,y)= (1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3 ,2),(3 ,3)

是否有已经执行此任务的排序例程?例行公事 如果没有测量图案的某些坐标,也应该可以工作。

谁能给我一些线索,我不是一个有经验的c++ 程序员,但也许有一些提示我可以完成这项工作!

【问题讨论】:

  • 使用排序和自定义比较?
  • 我不认为这是自定义比较。

标签: c++ algorithm data-structures array-algorithms


【解决方案1】:
bool compare_coord(pair<int, int> &coord1, pair<int, int> &coord2){
    if(coord2.second > coord1.second)
        return true;
    if(coord2.second == coord1.second && coord2.first > coord1.first)
        return true;
    return false;
}

【讨论】:

    【解决方案2】:

    你需要一个稳定的排序算法(女巫不会改变相等元素的顺序)。先按y坐标排序,再按x排序,得到想要的结果:

    std::stable_sort(points.begin(), points.end(), yComparator());
    std::stable_sort(points.begin(), points.end(), xComparator());
    

    例如:
    之前:(x,y)= (2,2),(2,3),(1,2),(1,3),(2,1),(1,1),(3,2), (3,3),(3,1)
    按 y 排序:(x,y)= (2,1),(1,1),(3,1),(2,2),(1,2),(3,2),(2,3 ),(1,3),(3,3)
    按 x 排序:(x,y)= (1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1 ),(3,2),(3,3)

    【讨论】:

      【解决方案3】:

      如果您知道数字的范围,您可以将 X 乘以某个大数,然后将 y 添加到该数字。现在您可以简单地对该单个数字进行排序,或者您可以使用 stl 库来按照其他人的描述进行排序。

      【讨论】:

        【解决方案4】:

        您可以使用std::sort 和自定义operator&lt; 来执行此操作,例如:

        #include <algorithm>
        #include <vector>
        
        struct coord {
          double x,y,quality;
        };
        
        bool operator<(const coord& a, const coord& b) {
          return a.quality < b.quality;
        }
        
        int main() {
          std::vector<coord> coords;
          std::sort(coords.begin(), coords.end());
        }
        

        如果您不希望将“质量”存储在结构中,您可以随时在operator&lt; 中直接调用一些函数来计算它,例如:

        double quality(const coord& c);
        
        bool operator<(const coord& a, const coord& b) {
          return quality(a) < quality(b);
        }
        

        【讨论】:

          猜你喜欢
          • 2021-08-30
          • 1970-01-01
          • 2018-12-07
          • 1970-01-01
          • 2021-10-06
          • 1970-01-01
          • 1970-01-01
          • 2012-07-22
          • 1970-01-01
          相关资源
          最近更新 更多