c++ - How can I access the members of objects stored in a vector? -
the code giving problem below. have commented parts give correct output, , not, not know why, , how should accessing class member data normally. read trying access in c style loop isn't great, tried ith iterators met "error: no match 'operator<=' (operand types 'player' , '__gnu_cxx::__normal_iterator >')"
class player { public: player() {} player(double strength) {} virtual ~player() {} double getstrength() const { return strength; } void setstrength(double val){ strength = val; } int getranking() const{ return ranking; } void setranking(int val){ ranking = val; } int getatppoints() const{ return atppoints; } void setatppoints(int val){ atppoints = val; } protected: private: double strength; //!< member variable "strength" int ranking; //!< member variable "ranking" int atppoints; //!< member variable "atppoints" }; int main() { vector<player> players(1000); // player strengths generated normal distribution mean of 5 , standard deviation of 2, values outside range of 0-10 discarded. generateplayerstrengths(players); sort(players.begin(), players.end(), sortmethod); // sort descending order int i=1; (player : players) { // initialise rank of players according strength a.setranking(i); i++; cout << a.getranking() << endl; // returns correctly } // returns zeros, random number, more zeros for(int j=0;j<32;j++) { cout << players[i].getranking() << endl; } cin.ignore(); // keep command window open debugging purposes. return 0; }
for (player : players)
in order modify objects in vector through a
, needs reference.
for (player& : players)
otherwise, working copies local loop body, , changes not seen when iterate next time.
also, using wrong index variable (i
, when should using j
) in second loop.
Comments
Post a Comment