简体   繁体   English

如何遍历填充有结构的数组?

[英]How can I iterate through a array filled with structures?

I'm trying to learn c++ for just a week now.我现在正在尝试学习 c++ 一个星期。 I want to iterate through a array filled with structures.我想遍历一个充满结构的数组。 This is the code that I have.这是我拥有的代码。

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} 
};

How can I using a for loop to show the output of this array?如何使用 for 循环来显示此数组的输出?

If you'll do it often, define a stream operator for your struct, then loop over them (see it live on Coliru ):如果您经常这样做,请为您的结构定义一个流运算符,然后循环遍历它们(在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';
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM