What's the simplest way of defining lexicographic comparison for elements of a class?

Tuple is a good idea, but if you want to keep having names for your member variables, it might be good enough to restructure your comparison function like this.

Tuple is a good idea, but if you want to keep having names for your member variables, it might be good enough to restructure your comparison function like this: struct MyData { string surname; string forename; string var; // ... bool operatorSurname; if (forename! = other. Forename) return forename Forename; if (var!

= other. Var) return var Var; // ... return false; //Field; to reduce duplication. Then the function would just become a list of COMPARE-invocations.

Maybe #define LEX_LT(mem) if(mem! = other. Mem) return mem Mem and then chain them as LEX_LT(surname); LEX_LT(forename); LEX_LT(var); ...; return false; – KennyTM Mar 23 '10 at 14:56 I like the layout of that, it's much more manageable and less error-prone than the nested-if.

I'm not averse to occasional macro use, and that could be handy for larger structures, but I think the basic form is clear enough. – the_mandrill Mar 23 '10 at 15:01.

You could store the data in a boost::tuple, which provides lexicographic comparison, and provide named accessor functions, along the lines of: struct Data { string &surname() {return stuff.get();} string &forename() {return stuff.get();} // it would be polite to add const overloads too. Bool operator stuff; }; I believe this is also available as std::tr1::tuple, and will be std::tuple in the forthcoming standard. Maintaining the list of accessors is probably more manageable than maintaining the comparison code.

1 Interesting solution. It seems a shame to lose the named fields though as seeing the class's contents in the debugger becomes more difficult. – the_mandrill Mar 23 '10 at 14:49 3 You can keep the named fields and use the tuple only for comparison purposes, e.

G return boost::tie(surname, forename) Then you only have to maintain a single list of the lexicographical order. – Mike Seymour Mar 23 '10 at 16:03 Neat - I hadn't come across boost::tie() before – the_mandrill Mar 23 '10 at 16:29.

If all members have the same type you could put them in std::vector. By default std::lexicographical_compare will be used to compare vectors.

You can use a boost::tuple or std::pair which has built-in lexigraphical comparison. Of course the disadvantage is you can't associate a method to the tuples.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions