Re: implement ORDER BY in c++
Niek Sanders wrote:
crazytora wrote:
I have a file which I want to sort depending on multiple
columns. Actually I want to implement the following query
through programming:
SELECT SUM(VALUES) GROUP BY x,y ORDER BY x,y;
the aggregation is complete.What I want is to order the
result.I have 7 fields which are used in GROUP BY clause and
I need to ORDER them with those fields.
You want to write your own sorting functor and then pass that
to STL's sort algorithm. For an example, see:
http://www.sgi.com/tech/stl/functors.html
("Sort a vector of double by magnitude....")
So you would have a functor that takes two result-row objects
as arguments, and spits out a bool indicating whether the
first argument comes before the second according to your
criteria.
That's the obvious solution. On the other hand, if he is really
implementing something along the lines of an SQL select, he's
probably scanning a complete container, extracting the relevant
fields in each object. In that case, two alternative solutions
come to mind:
-- maintain the destination array sorted, by using lower_bound
to determine where to insert, or by using a sorted container
for the results to begin with, maybe multi_set, OR...
-- since the only "value" he's really interested in is the sum
of the "VALUES" fields, I'd probably use an std::map<
XYPair, value_type >, where XYPair could even be a simple
typedef for std::pair< x_type, y_type >.
In the second case, his program ends up as simple at:
for ( C::const_iterator iter = container.begin() ;
iter != container.end() ;
++ iter ) {
result[ XYPair( iter->x(), iter->y() ) ] += iter->value() ;
}
The result is the sums, grouped by and ordered by x, y.
--
James Kanze GABI Software
Conseils en informatique orient?e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S?mard, 78210 St.-Cyr-l'?cole, France, +33 (0)1 30 23 00 34
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]