Sorting a Vector of Objects Based on An Attribute

Please Note: This is from a homework assignment, however, it was due like 3-4 weeks ago. I'm solely doing it for the learning aspect.

Also note that I checked: http://www.cplusplus.com/forum/general/100845/ which is a similar issue, but I tried modifying that code to work for my file and it didn't work. Although I wasn't 100% sure what "Car*" was representing in their code compared to my own files.

I'm trying to sort from a vector of objects based off one of the attributes of the objects. To be exact, I have a vector of players and I want to sort the objects in descending order based off the points each player has.

My class is called Player and has these member variables:
playerName (string)
teamName (string)
points (double)
rebounds (double)
assists (double)

My vector is declared in Main() as std::vector<Player> Players.
Then the vector is referred to as PlayersVec in other functions.

I am currently trying to sort it using:
sort(PlayersVec.begin().getPnts(), PlayersVec.end().getPnts(), std::greater<int>());

The errors are:
1
2
3
4
5
6
MainFunctions.cpp: In function ‘void sortData(std::vector<Player>&)’:
MainFunctions.cpp:413:33: error: ‘std::vector<Player>::iterator {aka class __gnu_cxx::__normal_iterator<Player*, std::vector<Player> >}’ has no member named ‘getPnts’
         sort(PlayersVec.begin().getPnts(), PlayersVec.end().getPnts(), std::greater<int>());
                                 ^~~~~~~
MainFunctions.cpp:413:61: error: ‘std::vector<Player>::iterator {aka class __gnu_cxx::__normal_iterator<Player*, std::vector<Player> >}’ has no member named ‘getPnts’
         sort(PlayersVec.begin().getPnts(), PlayersVec.end().getPnts(), std::greater<int>());


If needed I have provided my files below. Please note that the error line messages may be different than the actual lines because I've removed some comments.
Main.cpp: http://cpp.sh/8bppd
MainFunctions.cpp: http://cpp.sh/82edj (Most of the code is here)
Player.h: http://cpp.sh/9yml4 (Class file)
Player.cpp: http://cpp.sh/8wy5m (All Member Functions for Class)
Players.txt: http://cpp.sh/6bkan (Input file)


Help would be greatly appreciated, thanks!


Edit: I got it to half work after taking a look at this post: https://stackoverflow.com/questions/1380463/sorting-a-vector-of-custom-objects. Now it sorts them using a lambda expression but doesn't do it in descending order yet. The link may also explain how to do it in descending order, not sure yet.

Edit 2: Got it to work! :)
Last edited on
Topic archived. No new replies allowed.