如何访问存储在向量中的对象的成员?

whi*_*ell -1 c++ stl vector

给出问题的代码如下.我已经评论了哪些部分提供了正确的输出,哪些没有,但我不知道为什么,以及我应该如何正常访问类成员数据.我读到尝试在C风格循环中访问并不是很好,但我尝试使用迭代器只能遇到"错误:不匹配'运算符<='(操作数类型是'播放器'和'__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 are generated from a normal distribution with a mean of 5 and standard deviation of 2, with values outside the range of 0-10 discarded.
    GeneratePlayerStrengths(Players);

    sort(Players.begin(), Players.end(), SortMethod); // sort descending order

    int i=1;
    for (Player a : Players)
    {   // initialise the rank of the players according to their strength
        a.SetRanking(i);
        i++;
        cout << a.GetRanking() << endl; // returns correctly
    }

    // returns all zeros, then a random number, then more zeros
    for(int j=0;j<32;j++) {
       cout << Players[i].GetRanking() << endl;
    }


    cin.ignore(); // keep the command window open for debugging purposes.
    return 0;

}
Run Code Online (Sandbox Code Playgroud)

Ben*_*ley 5

for (Player a : Players)
Run Code Online (Sandbox Code Playgroud)

为了修改矢量中的对象a,需要将其作为参考.

for (Player& a : Players)
Run Code Online (Sandbox Code Playgroud)

否则,您正在使用循环体本地的副本,并且在下次迭代时将看不到更改.

此外,您在第二个循环中使用了错误的索引变量(i当您应该使用时j).