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

时间:2014-06-10 15:38:27

标签: c++ vector stl

提供问题的代码如下。我已经评论了哪些部分提供了正确的输出,哪些没有,但我不知道为什么,以及我应该如何正常访问类成员数据。我读到尝试在C风格循环中访问并不是很好,但我尝试使用迭代器只能遇到“错误:不匹配'运算符< ='(操作数类型是'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 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;

}

4 个答案:

答案 0 :(得分:5)

for (Player a : Players)

为了通过a修改向量中的对象,它需要作为参考。

for (Player& a : Players)

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

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

答案 1 :(得分:4)

在最后的for - 周期中,您会迭代j变量,但会使用i进行访问。

答案 2 :(得分:2)

在修正了本杰明指出的错误,在你打印的地方,你应该打印

Players[j].GetRanking() 

而不是

Players[i].GetRanking()

答案 3 :(得分:0)

考虑此代码:

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

在每次循环迭代中,您正在Player中对当前vector实例进行复制

因此,您在副本上调用SetRanking(),而不是Player中存储的原始vector实例。

要解决此问题,您可能需要考虑使用引用

for (Player& a : Players) // <-- note the & for reference
{
    ... same code ...
}

在这种情况下,a是对Player中存储的vector原始实例的引用(因此,在这种情况下,您不会制作副本)。

此外,您可能希望在StackOverflow上阅读this questionanswer

相关问题