如何迭代填充结构的数组?

时间:2017-02-06 14:08:46

标签: c++

我正在努力学习c ++一周。 我想遍历一个充满结构的数组。 这是我的代码。

struct PlayerState
{
    char name[20];
    int level;
    int year;
    double health;
    int experience;
};

PlayerState States[2] = { 
    { "Mike", 10, 2017, 10.0, 1}, 
    { "Mike", 10, 2017, 10.0, 1} 
};

如何使用for循环显示此数组的输出?

1 个答案:

答案 0 :(得分:0)

如果您经常这样做,请为您的结构定义一个流运算符,然后循环它们(请参见 Coliru ):

#include <iostream>

struct PlayerState
{
    char name[20];
    int level;
    int year;
    double health;
    int experience;
};

std::ostream& operator<< ( std::ostream& os, const PlayerState& state )
{
    os << state.name << ": " 
       << state.level << ", " 
       << state.year<< ", " 
       << state.health << ", " 
       << state.experience;
    return os; 
}

PlayerState States[2] = { 
    { "Mike", 11, 2017, 11.0, 1}, 
    { "Mike", 10, 2015, 10.0, 1} 
};

int main()
{
    for( const auto& state : States )
    {
        std::cout << state << '\n';
    }

    std::cout << '\n';

    for( auto i = 0u; i < sizeof( States ) / sizeof( PlayerState ); ++i )
    {
        std::cout << States[i] << '\n';
    }
}