首页 文章

什么是Vector语法

提问于
浏览
-1

这是我的功能:

void Gladiator::display()

{

  cout << name << ":\nHealth: " << curHealth << '/' << maxHealth <<

    "\nEvasion: " << evasion << "\nCritical: " << critical <<

    "\nDamage: " << dmgMin << '-' << dmgMin + dmgRange + 1 << "\n\n";

}

我需要帮助我的语法来显示上面函数的统计数据,以及我为蓝色和红色团队创建Gladiators矢量的语法是否正确?非常感谢 .

cout << "A battle will soon commence... First the Teams must be created." << endl;

        vector<Gladiator> redTeam; // is the syntax correct for this one too?

        vector<Gladiator> blueTeam;

        cout << "Red Team's Stats: " << endl;

        Gladiator.display(redTeam); //this is the part where I don't know the syntax of displaying the stats for redTeam vector.

        cout << "Blue Team's Stats: " << endl;

        blueTeam.display(); //syntax for this is wrong too.

4 回答

  • 0

    关于 Gladiator.display(redTeam); :不, display 不接受参数,也不接受 . 这是一个显示一个 Gladiator 的统计数据的功能,理想情况下,它应该与角斗士争夺的团队无关 .

    相反,创建一个 Team 类来保存Gladiator的向量并向其添加一个 display 成员函数,它循环通过所有角斗士并调用它们的 display 函数 .

    struct Team {
        void display() const {
            for(const Gladiator& g : gladiators) {
                g.display();
            }
        }
    };
    

    当你以后想要添加用于打击另一个团队的功能时, Team 类也会派上用场 . 然后 Team 类中的 Fight 函数将调用其包含的Gladiator上的 Fight 函数 .

    两个 display 函数都可以组成流操作符,以便与标准流无缝集成,以便您可以这样做:

    std::cout << a_gladiator; // print stats for one gladiator
    std::cout << redteam;     // print stats for all gladiators in a team
    

    这里's an example where I'已经用流操作符替换了 display 函数,因为随机性可能是战斗的重要部分,我也添加了 <random> 库的示例用法以及如何在两个类中实现 Fight 函数的示例 .

    #include <iostream>
    #include <vector>
    #include <random>
    
    // "prng" will be the pseudo random number generator when fighting
    // https://en.cppreference.com/w/cpp/header/random
    std::random_device rd;
    std::mt19937 prng(rd());
    
    enum Result { r_loss=-1, r_draw=0, r_win=1};
    
    Result win_or_loss(int h, int a) {
        int r = h-a;
        return (r==0) ? r_draw : (r>0?r_win:r_loss);
    }
    //-----------------------------------------------------------------------------
    struct Gladiator {
        std::string name;
        int maxHealth;
        int curHealth;
        int evasion;
        int critical;
        // "damage" will hold the min and max values of damage
        // and can be used with a pseudo random number generator
        // to get the value of one strike that the Gladiator
        // delivers
        std::uniform_int_distribution<int> damage;
    
        Gladiator(const std::string& Name, int MaxHealth, int Evasion,
                  int Critical, int DmgMin, int DmgRange) :
            name(Name),
            maxHealth(MaxHealth),
            curHealth(maxHealth),
            evasion(Evasion),
            critical(Critical),
            damage(DmgMin, DmgMin+DmgRange) // initialize with DmgMin and DmgRange
        {}
    
        // return r_win if this gladiator wins or r_loss if the opponent wins
        //        or r_draw if it's a draw
        Result Fight(Gladiator& opponent) {
            // perhaps reset health here, or at the end of the fight
            curHealth = maxHealth;
            opponent.curHealth = opponent.maxHealth;
    
            std::cout << " The fight between " << name << " and " << opponent.name << " begins!\n";
            // fight loop
            while( curHealth>0 && opponent.curHealth>0 ) {
                // use of evasion & critical must be added
    
                // use the "damage" uniform int distributions with the
                // random number generator to get the values for the hits
                int my_hit = damage(prng);
                int opponents_hit = opponent.damage(prng);
                // add cool fight messages
                std::cout << "  " << name << " hit " << opponent.name << ", doing " << my_hit << " hp damage.\n";
                std::cout << "  " << opponent.name << " hit " << name << ", doing " << opponents_hit << " hp damage.\n";
                curHealth -= opponents_hit;
                opponent.curHealth -= my_hit;
            }
            // figure out who won
            Result r = win_or_loss(curHealth, opponent.curHealth);
            if(r==r_win) std::cout << " Gladiator " << name << " won!\n";
            else if(r==r_loss) std::cout << " Gladiator " << opponent.name << " won!\n";
            else std::cout << " It was a draw!\n";
            return r;
        }
    
        // declare a function (in the form of a stream operator) for streaming
        // a gladiator to an output stream, like std::cout
        friend std::ostream& operator<<(std::ostream&, const Gladiator&);
    };
    
    // definition of the output stream operator for a Gladiator
    std::ostream& operator<<(std::ostream& os, const Gladiator& g) {
        os << " " << g.name << ":\n  Health: " << g.curHealth << '/' << g.maxHealth <<
            "\n  Evasion: " << g.evasion << "\n  Critical: " << g.critical <<
            "\n  Damage: " << g.damage.min() << '-' << g.damage.max() << "\n\n";
        return os;
    }
    //-----------------------------------------------------------------------------
    struct Team {
        std::string name;
        std::vector<Gladiator> m_gladiators;
    
        Team(const std::string& Name) : Team(Name, {}) {}
        Team(const std::string& Name, std::vector<Gladiator>&& gv) :
            name(Name),
            m_gladiators(std::move(gv))
        {}
    
        // return r_win if this team wins or r_loss if the opponent team wins
        //        or r_draw if it's a draw    
        Result Fight(Team& opponent) {
            unsigned wins=0, losses=0;
            std::cout << "Team " << name << " vs. " << opponent.name << "\n";
            for(Gladiator& my_gladiator : m_gladiators) {
                for(Gladiator& opponent_gladiator : opponent.m_gladiators) {
                    Result result = my_gladiator.Fight(opponent_gladiator);
                    if(result>0) {
                        ++wins;
                    } else if(result<0) {
                        ++losses;
                    }
                }
            }
            Result r = win_or_loss(wins, losses);
            if(r==r_win) std::cout << "Team " << name << " won!\n";
            else if(r==r_loss) std::cout << "Team " << opponent.name << " won!\n";
            else std::cout << "It was a draw\n";
            return r;
        }
    
        // Just like for an individal Gladiator, declare a stream operator.
        friend std::ostream& operator<<(std::ostream&, const Team&);
    };
    
    // stream all gladiators in a Team
    std::ostream& operator<<(std::ostream& os, const Team& t) {
        os << "Team " << t.name << " stats:\n";
        for(const auto& g : t.m_gladiators) {
            std::cout << g; // this uses the Gladiator output stream operator
        }
        return os;
    }
    //-----------------------------------------------------------------------------
    
    int main() {
        std::cout << "A battle will soon commence... First the Teams must be created.\n";
    
        // if you'd like a dynamic amount of teams, you can make a Team vector like this:
        std::vector <Team> teams = {
            {"Red",
                {
                    {"Spartacus", 100, 25, 27, 10, 17},
                    {"Crixus",     99, 24, 26, 12, 13}
                }
            },
            {"Blue",
                {
                    {"Commodus",  101, 30, 28, 11, 16},
                    {"Tetraites",  98, 31, 29, 10, 15}
                }
            }
        };
    
        // print info about all teams
        for(const auto& team : teams) std::cout << team;
    
        // let all teams fight
        for(auto it_a=teams.begin(); it_a<(teams.end()-1); ++it_a) {
            for(auto it_b=it_a+1; it_b<teams.end(); ++it_b) {
                (*it_a).Fight(*it_b);
            }
        }
    
        /*
        std::cout << "------\n";
    
        // or if you'd like to treat them separately, you can create
        // referenses to the teams:
    
        Team& redTeam = teams[0];
        Team& blueTeam = teams[1];
    
        // and use them individually
        std::cout << redTeam;
        std::cout << blueTeam;
    
        redTeam.Fight(blueTeam);
        */
    }
    
  • 1

    你有一种误解 . 函数 Gladiator::Display() 是类 Gladiator 的成员函数 . 该函数不接受任何参数,因此您无法按原样调用它 .

    我建议你寻找 function overloadingstatic 函数,因为它们可以帮助你理解你需要做什么 .

    我会添加一个 static 函数 Galdiator::Display(const std::vector<Gladiator>& team) ,如下所示:

    Gladiator.h

    class Gladiator{
    public:
        //.. your functions
        void Display() const; // PLEASE ADD TRAILING const TO ALLOW THIS FUNCTION TO BE CALLED ON const Gladiator objects.
        static void Display(const std::vector<Gladiator>& team);
    private:
        // data
    }
    

    Gladiator.cpp

    static void Gladiator::Display(const std::vector<Gladiator>& team){
         for(auto& glad : team)
             glad.Display();
    }
    

    然后你就可以称之为:

    Gladiator::Display(redTeam); // or blueTeam
    

    请注意,不能像_47582中那样使用 extension methods ,您可以使用静态类扩展现有类 . 因此,无法致电:

    blueTeam.Display();
    

    由于 blueTeamstd::vector ,它不包含函数 Display() .

    但是,您可以使用流操作符重载和重载 std::ostream 来解决方法,使其接受 std::vector<Gladiator> 并显示它 . 我不建议你深入研究这个问题,因为问题表明在一些基础知识方面缺乏知识 .


    无论如何,这个:

    vector<Gladiator> redTeam;
    

    如果 Gladiator 存在默认构造函数,则完全有效 . 如果你想给它一个尺寸,你可以使用:

    int n = 10; // number of gladiators per team
    vector<Gladiator> redTeam(n);
    

    这将在其中创建一个带有 10 Gladiators的向量 . 请注意,这仅在IF Gladiator 具有默认构造函数 Gladiator::Gladiator() 时才有效 . 如果您创建了另一个构造函数,编译器将不会自动生成默认构造函数 .

    希望这可以帮助 .

  • 0
    std::vector<Gladiator> v = {};
    
    v.push_back(Gladiator());
    
    // Iterate and print values of vector
    for(Gladiator g : v) {
        g.Display();
    }
    

    https://en.cppreference.com/w/cpp/container/vector

    有关详细信息,请参阅以下内容

    How can I create objects while adding them into a vector?

  • -1

    首先,虽然语法有效,但此处的向量为空:

    vector<Gladiator> redTeam;
    

    因此,您需要在显示任何内容之前向该向量添加元素 .
    有关该主题的更多信息,请参阅std::vector::push_back .


    这里的语法错误:

    Gladiator.display(redTeam);
    

    display 函数不带任何参数 . 你打算做的是(假设你在向量中添加了一些元素):

    for (const auto& elm : redTeam) {
        elm.display();
    }
    

    这里我们在向量中的每个元素上调用 display 方法 .
    有关该主题的更多信息,请参见Range-based for loop .

相关问题