How to access instance variable value?

I created n objects from the Stock class and assigned a value for the integer instance variable expectancy. This value is different for each object (stock). I want to order objects descending according to expectancy. How can I achieve that?

1
2
Stock* stock = new Stock [n];
stock[counter].expectancy = ............;

Last edited on
http://www.cplusplus.com/reference/algorithm/sort/
You want the version with the third argument, a comparator.

You don't have a good record of acknowledging replies in previous threads.
if the object is large and you need to sort it multiple ways, you may want a container of pointers to the original data and sort the pointers instead of the real data. This is more of a real world answer, than homework.
a) why use dynamic memory instead of a vector?

b) if you just want to hold them sorted by .expectancy, an option would be to use a std::set with a custom comparator http://www.cplusplus.com/reference/set/set/

I used this code but it doesn't work and I don't know why. Could you please help?
sort(stock[0].expectancy, stock[lastElementIndex].expectancy, greater<int>());
Last edited on
@seeplus I don't understand what you mean. If you have a solution using vectors please show it to me.
1
2
3
4
vector<Stock> shares( n );
...
...
sort( shares.begin(), shares.end(), []( Stock a, Stock b ){ return a.expectancy > b.expectancy; } );
Last edited on
Topic archived. No new replies allowed.