1. vector: sort multiple fields

I have a struct-based vector with 7 fields (strings). I need to sort by 5 of these fields. Easy in SQL, but not quite as simple in a vector, I think.

I found this code via google and was wondering if it's a good basis for my need.

Code:
#include <algorithm>
#include <vector>
#include <cstdlib>

class MyClass
{
public:
double value1;
double value2;
double value3;

// Friends not necessary with public data,
// required with private data.
friend bool less1(const MyClass& a, const MyClass& b);
friend bool less2(const MyClass& a, const MyClass& b);
friend bool less3(const MyClass& a, const MyClass& b);
friend bool less_sum(const MyClass& a, const MyClass& b);

};

inline bool less1(const MyClass& a, const MyClass& b)
{ return a.value1 < b.value1; }

inline bool less2(const MyClass& a, const MyClass& b)
{ return a.value2 < b.value2; }

inline bool less3(const MyClass& a, const MyClass& b)
{ return a.value3 < b.value3; }

inline bool lessSum(const MyClass& a, const MyClass& b)
{ return (a.value1 + a.value2 + a.value3) < (b.value1 +
b.value2 + b.value3); }

main() {
std::vector<MyClass> mcVec(10);

// Sort by value1
std::sort(mcVec.begin(), mcVec.end(), less1);

// Sort by value2
std::sort(mcVec.begin(), mcVec.end(), less2);

// Sort by value3
std::sort(mcVec.begin(), mcVec.end(), less3);

// Sort by sum of all three values
std::sort(mcVec.begin(), mcVec.end(), lessSum);

return EXIT_SUCCESS;

} // end main()

2. Yes. That is exactly what you need. Each one of the less functions sorts in a different way. If you need to sort by all five strings at the same time (like in a SQL order by), create a less function like one of those above, and inside the function compare each string one at a time. For the first string, if a's version is less than b's version, then return true. If it is greater, return false. If they are equal, continue on to the next string. Do this for all five strings. If all five strings are equal, make sure you return false.

Assuming C++ strings. I think the best way to compare them is using the compare method, sort of like this:
Code:
int res = a.firstString.compare(b.firstString);
if (res < 0) return true;
if (res > 0) return false;

res = a.secondString.compare(b.secondString);
if (res < 0) return true;
if (res > 0) return false;

// ...
Another day, another vector/string question from FoodDude answered by Daved.

3. Another thank you.

4. Since the greater than and less than operators are defined for strings it would be even easier to just have:
Code:
if (a.firstString < b.firstString) return true;
// ...

5. That might be a tiny bit clearer, but it would mean that you need to compare each pair of strings twice, which is why I saved the result. If there is only one pair of strings to compare, then you would use that form since greater than and equal would both have the same result.