Vector sort?
Can someone show me how to implement qsort() with vectors
Here''s my code (parts of it)
struct duo
{
int len;
int index;
int num;
};
vector final;
qsort(final, final.size(), sizeof(struct duo), comp);
and I''m getting an error that I can''t use "final" as my first argument to qsort because it can''t be const void*
Please Help!
There is already a sort function for collections in the Standard Template Library. It takes a "start" and "end" iterator (and optionally an object that will do the comparisons; otherwise it just sorts in ascending order). For example:
In fact, you can also use it for regular arrays if you want to, since pointers are treated as iterators by the STL. For example, if you have an array ar of size 10, you can call sort(ar, ar+10).
[edited by - Matei on June 1, 2004 1:01:13 PM]
#include <algorithm>#include <vector>#include <cstdio>using namespace std;int main() { vector<int> v; v.push_back(3); v.push_back(1); v.push_back(2); printf("before: %d, %d, %d\n", v[0], v[1], v[2]); sort(v.begin(), v.end()); // <-- this is it! printf("after: %d, %d, %d\n", v[0], v[1], v[2]);}
In fact, you can also use it for regular arrays if you want to, since pointers are treated as iterators by the STL. For example, if you have an array ar of size 10, you can call sort(ar, ar+10).
[edited by - Matei on June 1, 2004 1:01:13 PM]
Well I could use that... but what I was really hoping for was to be able to use a quick sort with a vector of structures...anybody know?
std::sort() probably already uses quicksort and/or some
other optimizations that you didn''t even think of or know about.
Is there a reason why you insist on using qsort()?
Mixing C (qsort) and C++ (vector) is not such a good idea.
Kami no Itte ga ore ni zettai naru!
other optimizations that you didn''t even think of or know about.
Is there a reason why you insist on using qsort()?
Mixing C (qsort) and C++ (vector) is not such a good idea.
Kami no Itte ga ore ni zettai naru!
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement