1

I want to std::sort a vector full of three dimensional points in a way that each point is primarily aligned based on the z value, secondarily by y value, and at last by the x value.

A desired output example could be

192 1 1
200 1 1
208 1 2
-296 2 2
-288 2 3

However, my approach to std::sort seems to be not very nice. On the one hand there is an == on a float. On the other hand my functor is rather complicated. Additionally, this approach sucks if I have a N-dimensional point. Is there a better way?

Example code:

// Example program
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <stdio.h>

struct point {
  float x;
  float y;
  float z;
};

int main()
{
    std::vector<point> foo = {
        { 1 ,  72 , 10 },
        { 2 ,  72 , 9 },
        { 3 ,  72 , 8 },
        { 32 ,  71 , 7 },
        { 4 ,  70 , -152 },
        { 32 ,  72 , -144 },
        { 5 ,  72 , -136 },
        { 5 ,  72 , -128 },
        { 5 ,  72 , -120 },
        { 32 ,  72 , -112 },
        { 32 ,  72 , -104 },
        { 32 ,  72 , -96 },
        { 32 ,  72 , -88 },
        { 32 ,  3 , -80 }
    };

  std::sort(
    foo.begin(),
    foo.end(),
    [](const point &a, const point &b) {
    if (a.z < b.z) return true;
    if (a.z == b.z && a.y < b.y) return true;
    if (a.z == b.z && a.y == b.y && a.x < b.x) return true;
    return false;
    }
  );

  for(auto p : foo) {
      printf("%f,%f,%f\n", p.x, p.y, p.z);
  }
}
dgrat
  • 2,214
  • 4
  • 24
  • 46

0 Answers0