Re: Implement ORDER BY clause in c++
Index wrote:
I have a file which I want to sort depending on multiple columns.
It depends where your data are located, and how they are represented. If
your records fit in the memory, you could store them in an STL vector,
then define a custom ordering operator.
Here's how to create a function object that orders by two fields (first
by "priority", and if they are the same, then by "size"):
struct Record
{
int priority;
int size;
[...] // other members
};
struct OrderByPriorityThenSize
{
bool operator()(const Record& lhs, const Record& rhs) const
{
if(lhs.priority == rhs.priority)
return lhs.size < rhs.size; // secondary ordering
else
return lhs.priority < rhs.priority; // primary ordering
}
};
Then assuming you have a vector of Record's, you can sort them using
your defined order:
std::vector<Recrod> items;
[...] // load the items
std::sort(items.begin(), items.end(), OrderByPriorityThenSize());
[...] // save the items
There are some ultra lightweight database engines available, such as
SQLite. That way you can use SQL queries to manage your data.
I'm not sure if this answers your question. If not, you'll need to
provide more details about your project.
Tom