最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c++ - Overloading comparison operators for simple `struct`s holding many numerical fields - Stack Overflow

programmeradmin4浏览0评论

Say I have got a plain old data (POD) struct containing multiple numeric fields.

I want to overload the comparison operators so that I can compare two instances of my POD.

The problem is that I need an overload for those operators - say, operator less() - for each of the numerical fields in the POD.

Obviously, the below does not work because the compiler has no way to pick the two versions apart:

struct my_struct{
    int a;
    int b;
    int c;
};

bool operator<(const my_struct& one, const my_struct& two) {
    return one.a < two.a;
}

bool operator<(const my_struct& one, const my_struct& two) {
    return one.b < two.b;
}

So I wrote my own custom function lessThan(), which accepts a flag and does the job, but I don't particularly like this solution (in MWE below) as I cannot use < as I easily would with a comparison operator.

#include <iostream>
#include <iomanip>

struct my_struct{
  int a;
  int b;
  int c;
};

bool lessThan(const my_struct& one, const my_struct& two, const char flag) {
  switch (flag) {
    case 'a':
      return one.a < two.a;
      break;
    case 'b':
      return one.b < two.b;
      break;        
    case 'c':
      return one.c < two.c;
      break;
    default:
      throw("Either case a, b, or c\n");
      break;
  }     
}

int main()
{
  my_struct one{1, 3, 4};
  my_struct two{2, 2, 4};
  std::cout << "one < two: " << std::boolalpha 
            << lessThan(one, two, 'a') << std::endl;

  return 0;
}

Is there a way to somehow create multiple comparison operator overloads for custom POD structs with many numerical fields, with each overload comparing one of those fields?

(To give you more context, I need those overloads for sorting an array of files according to any of their characteristics: such as by dimension, by last modification date, by number of contained files or subdirectories, etc.

In the simplified example above, each POD instance abstracts a file.)


EDIT:

Sketch of intended usage:

sortAccordingToFieldA(std::vector<my_struct>& my_vec, int a){
  for (auto i : my_vec) {
    for (auto j : [my_vec.begin()+i+1, my_vec.end()] ) {
      if (i < j)  // here '<' is overloaded according to field 'a'
        // sorting operations
    }
  } 
}
发布评论

评论列表(0)

  1. 暂无评论