Jump to content
  • Advertisement

Archived

This topic is now archived and is closed to further replies.

Penguinzchaseme

Vector sort?

This topic is 5282 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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!

Share this post


Link to post
Share on other sites
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]

Share this post


Link to post
Share on other sites
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!

Share this post


Link to post
Share on other sites
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?

Share this post


Link to post
Share on other sites
This provides an example of using a comparer function. It''s better than overloading a comparison operator for such a simple structure.

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!