Public Group

#### Archived

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

# 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.

## 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 on other sites
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 on other sites
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?

##### 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 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 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.

1. 1
Rutin
40
2. 2
3. 3
4. 4
5. 5

• 18
• 19
• 12
• 14
• 9
• ### Forum Statistics

• Total Topics
633362
• Total Posts
3011531
• ### Who's Online (See full list)

There are no registered users currently online

×