Re: Implementing ORDER BY clause in c++
In article <1148857630.230937.24620
@y43g2000cwc.googlegroups.com>,
kasturi.chatterjee@gmail.com says...
Hi,
Thanks for all the inputs.But what I understand from all this that at
any instant, the std:sort uses only one key to sort.
std::sort uses whatever result is returned by operator<
(or the specified functor) to determine the order. That
can be based on as many fields as you prefer.
All you have to define is the relative ordering of any
two keys and encode that into your comparison function.
std::sort can handle things from there.
For example:
struct data {
int x, y, z;
bool operator<(data const &other) {
if (x<other.x)
return true;
if (x>other.x)
return false;
// x == other.x, check y
if (y<other.y)
return true;
if (y>other.y)
return false;
// x==other.x, y==other.y, check z
if (z<other.z)
return true;
return false;
}
}
Now, std::sort(some_data.begin(), some_data.end())
produces the same ordering as 'order by x, y, z' would in
SQL -- order primarily by x, and if the x's are equal
order by y, and if the y's are equal, order by z.
If you need the equivalent of different order by clauses,
you have to write up each one, and specify the correct
one when you call std::sort:
// define the ordering.
struct by_yz {
bool operator()(data const &a, data const &b) {
if (a.y<b.y)
return true;
if (a.y>b.y)
return false;
if (a.z<b.z)
return true;
return false;
}
};
// sort data equivalent to 'order by y, z' in SQL:
std::sort(some_data.begin(), some_data.end(), by_yz);
--
Later,
Jerry.
The universe is a figment of its own imagination.