473,513 Members | 3,076 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

sorting a vector

8 New Member
Hi All
I was just wondering if its possible to use the sort method found in the STL algorithms class on a vector I declared as: " vector<myClass> myVector; "
where I want to sort according to one of the instance varaibles of myClass.

Thanks
Apr 21 '07 #1
9 2751
JosAH
11,448 Recognized Expert MVP
Hi All
I was just wondering if its possible to use the sort method found in the STL algorithms class on a vector I declared as: " vector<myClass> myVector; "
where I want to sort according to one of the instance varaibles of myClass.

Thanks
Sure, simply define an overloaded operator< for your class and sort the vector
given the two iterators v.begin() and v.end().

kind regards,

Jos
Apr 21 '07 #2
weaknessforcats
9,208 Recognized Expert Moderator Expert
If you don't have operator< implemented in your class, then you can use the sort algorithm where you pass in iterators to the begin and end of the sort range and a binary predicate.

The binary predicate is a function you write that takes two or your vector elements as arguments and returns true if the first argumenrt is less than the second argument. The sort algorithm will call this function to compare your vector elements.
Apr 21 '07 #3
BEEMZA
8 New Member
Hi All

I posted earlier.....
I took advise on using the sort method in the STL under algorithms on a class that I created. Here is the operator overloading that i did but i cant seem to get it to sort at all. PLease help

Expand|Select|Wrap|Line Numbers
  1. bool info::operator < (info &b){
  2.     if ( (*this).getWeight() < b.getWeight() )
  3.     return true;
  4.     else
  5.     return false;
  6. }
Apr 22 '07 #4
AdrianH
1,251 Recognized Expert Top Contributor
Hi All

I posted earlier.....
I took advise on using the sort method in the STL under algorithms on a class that I created. Here is the operator overloading that i did but i cant seem to get it to sort at all. PLease help

Expand|Select|Wrap|Line Numbers
  1. bool info::operator < (info &b){
  2.     if ( (*this).getWeight() < b.getWeight() )
  3.     return true;
  4.     else
  5.     return false;
  6. }
I don't know the original problem. I'll have to look back to find it but am about to go to bed, so I'll do it tomorrow.

What you have posted probably should work. Did you get any compile errors, or warnings? If you are using gnu c++, try using the -Wall switch. It will spit out anything that looks suspicious.

One thing I would change which may be a factor is that the parameter should be constant as should the function you overloaded.

Other than that, the (*this).getWeight() can be expressed as simply getWeight() and you could just use return getWeight() < b.getWeight() instead of breaking it up with an if statement. However, your method can be useful when using certain debuggers.

Let me know if this helps. Otherwise, I'll see if I can read up on your last thread.


Adrian
Apr 22 '07 #5
AdrianH
1,251 Recognized Expert Top Contributor
Hi BEEMZA,

I would like to say to you and all other posters that we at The Scripts Developer Network (TSDN) are happy to help you with your problems.

However, it is inappropriate to PM (send a personal message) to anyone regarding a question that should be posted to a forum unless explicitly requested to do so. There are many reasons for this including, a) the person that you are PMing may not be around all the time, b) if everyone PMed instead of using the forums then others may not be able to help or learn from your problems. Also, it may flood a single users PM box which is not good either.

Please look at the posting guidelines to learn the ways of the site and reduce the risk of offending other users, no matter what their relationship to the site is.
Unfortunately, I feel that I cannot continue this thread until you pass the information you passed on to me to this forum, as an act that you understand what I am saying.

I hold no hard feelings towards you, as I hope you do not to me either.


Adrian
Apr 22 '07 #6
weaknessforcats
9,208 Recognized Expert Moderator Expert
I would like to see your sort() call.
Apr 22 '07 #7
BEEMZA
8 New Member
I am trying to sort a vector containing objects of a class, using one of the instance variables as a key(int).

I defined the operator overload as follows:

Expand|Select|Wrap|Line Numbers
  1. bool info::operator < (info &b){
  2.     return getWeight() < b.getWeight();
  3.  
  4. }
In the driver i have included <algorithm> and am using the sort method as follows:

sort ( myVector.begin(), myVector.end() )

but this does not sort the vector at all.

Pls help
Apr 22 '07 #8
AdrianH
1,251 Recognized Expert Top Contributor
Hi again,

When replying to a message, please do not start a new thread. Click on the reply button at the bottom of the thread listing. What you are doing is considered double posting and is frowned upon (you can get booted off the site if it continues). At this point, I am assuming that you are having difficulties understanding how to post as this is the second time I have merged this thread.

Please reply to this thread so that we can help you. The post will come up to the beginning of the list of posts when someone (you or anybody else) replies to the thread, so you do not have to start a new thread to get our attention. Right now you are getting the wrong attention, the type that doesn't make me want to help you. So please smarten up, as my patience has its limits.

As for sorting, see http://www.cplusplus.com/reference/algorithm/sort.html for more information.

Thank you,


Adrian
Apr 22 '07 #9
weaknessforcats
9,208 Recognized Expert Moderator Expert
This looks correct:
Expand|Select|Wrap|Line Numbers
  1. sort ( myVector.begin(), myVector.end() )
  2.  
I would now like to see your class declaration and your main().

I assume you have put a breakpoint in your info::operator< and run the the programusing your debugger to verify that the info::operator< function is being called by the sort. Yes?
Apr 23 '07 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

5
3397
by: Pratyush | last post by:
Hi, Suppose there is a vector of objects of class A, i.e., std::vector<A> vec_A(N); The class A satisifies all the STL vector requirements. Now I wish to add some attributes for each of the objects in the vector vec_A. Suppose there are K attributes to be added. For each of the attributes I define K vectors of appropriate types. Say, the...
3
4605
by: cylin | last post by:
Dear all, After sorting a vector, how to get max in this vector? I got a strange result of my test code. ------------------------------------------------- #include <iostream> #include <vector> #include <algorithm> using namespace std;
0
2644
by: Alex Vinokur | last post by:
=================================== ------------- Sorting ------------- Comparative performance measurement =================================== Testsuite : Comparing Function Objects to Function Pointers Source : Technical Report on C++ Performance Tool : The C/C++ Program Perfometer (Version 2.8.1-1.19-Beta) *...
18
3022
by: Matthias Kaeppler | last post by:
Hi, in my program, I have to sort containers of objects which can be 2000 items big in some cases. Since STL containers are based around copying and since I need to sort these containers quite frequently, I thought it'd be a better idea to manage additional containers which are initialized with pointers to the objects in the primary...
2
4127
by: fred_stevens | last post by:
Hi all you C boffins: I need to sort a vector of doubles is ascending order. Qsort will return the sorted vector, but I need a vector of the indices of the sorted vector, not the actual sorted vector. Any ideas? Thanks in advance, Fred.
9
2820
by: Daz | last post by:
Hello people! (This post is best viewed using a monospace font). I need to create a class, which holds 4 elements: std::string ItemName int Calories int Weight int Density
0
2557
by: SvenMathijssen | last post by:
Hi, I've been wrestling with a problem for some time that ought to be fairly simple, but turns out to be very difficult for me to solve. Maybe someone here knows the answer. What I try to do is sort the records in a plain-text index file based on certain columns. The index file consists of records and fields within the records. The...
3
1884
by: Pino | last post by:
HI all, I am learning c++ ( just 1 month) and would want an aid for a code. I have a integer vector of length N. ie 3 3 3 4 4 1
11
1986
by: Trent | last post by:
Running this I see that on first run, both bubble and selection sort have 9 sort counts while insertion sort has ZERO. With a sorted list, should this be ZERO for all? Also bsort and Ssort have the same exact sorting counts also..shouldn't they differ somewhat? Source and data file below. Thanks
6
2172
by: Tim Frink | last post by:
Hi, I need some help with STL lists. I've a list with pointers to some objects, let's say std::list< ObjectA* myList. The objects of the class ObjectA all have a function "int getIntValue()". What I need
0
7269
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7177
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7559
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7123
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
5701
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5100
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3248
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3237
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
470
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.