Vector sort?

Started by
4 comments, last by Penguinzchaseme 19 years, 10 months ago
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!
When Penguins are chasing you, resistance is futile, give into their demands and they may spare you
Advertisement
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:
#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?
When Penguins are chasing you, resistance is futile, give into their demands and they may spare you
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!
神はサイコロを振らない!
No I guess there''s no reason, but now I can''t figure out how to use sort() with three arguments, can someone show me how to write a comparison function?
When Penguins are chasing you, resistance is futile, give into their demands and they may spare you
This provides an example of using a comparer function. It''s better than overloading a comparison operator for such a simple structure.

This topic is closed to new replies.

Advertisement