c++ - C++如何从链表中选择随机项目

标签 c++ pointers for-loop struct linked-list

我正在尝试一个游戏程序。我正在尝试生成随机数量的项目。该代码将多次产生相同的项目。我可以设置一系列switch语句,从而产生多个搜索区域供玩家浏览,从而每个区域获得一个新的随机物品,但我想学习如何处理自己的问题这里做错了。没有什么能像错误一样帮助您学习。

我正在使用结构,链接列表,类和指针。

//genItem.h
#pragma once

struct item
{
    char itemName[50];
    int itemDamage;
    int itemStability;
    item* Next;
};

class genItem
{
public:
    genItem(void);
    ~genItem(void);
    int count();
    int add_item(item* currentItem);
    void generate_item(int d2, int s2);
    item *Head;
    item *Retrieve(int pos);
private:
    int size;
    int damage;
    int stability;
};

//genItem.cpp
#include <iostream>
#include "genItem.h"
#include <stdio.h> // NEED THIS FOR NULL TO WORK
#include <ctime>
using namespace std;

genItem::genItem(void)
    :size(0), Head(NULL)
{
}


genItem::~genItem(void)
{

}

int genItem::count()
{
    return size;
}

int genItem::add_item(item *thisItem)
{
    item *itemObject = new item;
    itemObject = thisItem;
    itemObject -> Next = Head;
    Head = itemObject;
    return size++;
}

item *genItem::Retrieve(int position)
{
    item *current = Head;
    for (int i = count() -1; i > position && current != NULL; i--)
    {
        current = current -> Next;
    }
    return current;
}

void genItem::generate_item(int d2, int s2)
{
    genItem *listItems = new genItem();
    item *listItem;

    srand (time(0));    

    int rn = 0;
    int total_in_cat = 10;
    int cat_item = 0;
    int rand_dam = rand();
    int rand_sta = rand();
    int per = rand();
    int base_d2 = 10;
    int base_s2 = 10;
    int rand_dam2 = rand();
    int rand_sta2 = rand();

    cat_item = per % total_in_cat;
    d2 = (rand_dam2 % base_d2) +2;
    s2 = (rand_sta2 % base_s2) + 2;

        if (rn == 0) // mushrooms
        {
            if(cat_item == 0)
            {
                listItem = new item;
                strcpy_s(listItem -> itemName, "an earthball mushroom");
                listItem -> itemDamage = d2;
                listItem -> itemStability = s2;
                listItems -> add_item(listItem);
            }
            else if (cat_item == 1)
            {
                listItem = new item;
                strcpy_s(listItem -> itemName, "a devil's bolete mushroom");
                listItem -> itemDamage = d2;
                listItem -> itemStability = s2;
                listItems -> add_item(listItem);
            }
            else if (cat_item == 2)
            {
                listItem = new item;
                strcpy_s(listItem -> itemName, "a rotting jack o'lantern mushroom");
                listItem -> itemDamage = d2;
                listItem -> itemStability = s2;
                listItems -> add_item(listItem);
            }
            else if (cat_item == 3)
            {
                listItem = new item;
                strcpy_s(listItem -> itemName, "a fly agaric mushroom");
                listItem -> itemDamage = d2;
                listItem -> itemStability = s2;
                listItems -> add_item(listItem);
            }
            else if (cat_item == 4)
            {
                listItem = new item;
                strcpy_s(listItem -> itemName, "a poison pie mushroom");
                listItem -> itemDamage = d2;
                listItem -> itemStability = s2;
                listItems -> add_item(listItem);
            }
            else if (cat_item == 5)
            {
                listItem = new item;
                strcpy_s(listItem -> itemName, "a mature deathcap mushroom");
                listItem -> itemDamage = 50;
                listItem -> itemStability = s2;
                listItems -> add_item(listItem);
            }
            else if (cat_item == 6)
            {
                listItem = new item;
                strcpy_s(listItem -> itemName, "a shaggy inkcap mushroom");
                listItem -> itemDamage = d2;
                listItem -> itemStability = s2;
                listItems -> add_item(listItem);
            }
            else if (cat_item == 7)
            {
                listItem = new item;
                strcpy_s(listItem -> itemName, "a bleeding milkcap mushroom");
                listItem -> itemDamage = d2;
                listItem -> itemStability = s2;
                listItems -> add_item(listItem);
            }
            else if (cat_item == 8)
            {
                listItem = new item;
                strcpy_s(listItem -> itemName, "a velvet shank mushroom");
                listItem -> itemDamage = d2;
                listItem -> itemStability = s2;
                listItems -> add_item(listItem);
            }
            else if (cat_item == 9)
            {
                listItem = new item;
                strcpy_s(listItem -> itemName, "a destroying angel mushroom");
                listItem -> itemDamage = 100;
                listItem -> itemStability = s2;
                listItems -> add_item(listItem);
            }
        } //end group 0

    damage = d2;
    stability = s2;

    int j = rand();
    for (int j =0; j <= 3; j++)
    {
        cout << "\tJ equals: " << j << endl;
    for (int i =0; i < listItems -> count(); i++)
        {   
            item *found = listItems -> Retrieve(i);
            cout << "\tYou have found " << found -> itemName << "." << endl;
            cout << "\tIt has a damage rating of " << found -> itemDamage;
            cout << " and a stability rating of " << found -> itemStability << "."<< endl;
            cout << endl;
        }
    }
}

//main.cpp
#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <stdlib.h>
#include <ctime>
#include "genItem.h"

using namespace std;

int main()
{   
genItem *findItem = new genItem;

int d2 = 0;
int s2 = 0;

findItem ->generate_item(d2, s2);

cout << "\t"; system("pause");
return 0;
}

最佳答案

现在您发布了更多的源代码,我可以为您提供更多信息,但这将是很长的时间。这也是一个非常本地化的问题,因此我将尝试尽可能广泛地回答,因为该回答对不仅仅是您的更多人有用。

一般问题

首先,让我们解决您的主要问题-仅显示一种项目,而不显示几种不同的项目。实际上,这可以通过调试程序来解决,甚至可以手动调试。跟踪,程序去向何处。开始了:

*** main.cpp, 17 ***
findItem ->generate_item(d2, s2);

(...)

*** getItem.cpp, 49 ***

int rn = 0;
...
int cat_item = 0;
...
    if (rn == 0) // mushrooms
    {
        if(cat_item == 0)
        {
            listItem = new item;
            strcpy_s(listItem -> itemName, "an earthball mushroom");
            listItem -> itemDamage = d2;
            listItem -> itemStability = s2;
            listItems -> add_item(listItem);
        }
...

*** getItem.cpp, 148 - continuing ***

damage = d2;
stability = s2;

int j = rand();
for (int j =0; j <= 3; j++)
{
    cout << "\tJ equals: " << j << endl;
for (int i =0; i < listItems -> count(); i++)
    {   
        item *found = listItems -> Retrieve(i);
        cout << "\tYou have found " << found -> itemName << "." << endl;
        cout << "\tIt has a damage rating of " << found -> itemDamage;
        cout << " and a stability rating of " << found -> itemStability << "."<< endl;
        cout << endl;
    }
}

这是您的程序在我指定的行中执行的操作:
  • 调用findItem-> generateItem;
  • rn设置为0并将cat_item设置为0
  • 基于rncat_item将单个项目添加到列表
  • 尝试显示列表中的随机元素,但是由于getItem::Retreive中的条件复杂,它始终返回Head(无论如何它始终是列表的唯一元素)。

  • 您无需在循环中将元素添加到列表中,因此仅显示一项就不足为奇了。

    建筑问题
  • 在这种情况下,列表的用法很糟糕。您需要通过元素的索引轻松访问元素,在这种情况下,std::vector会更好(更快,更易于维护和使用)。阅读more,了解C++ 11中不同数据结构的用法。
  • genItem类内部存在一些严重问题。它看起来像是所有可用项目的存储库,但是随后您在其中做了一些非常可疑的事情,例如:
    void genItem::generate_item(int d2, int s2)
    {
        genItem *listItems = new genItem();
    

    (在这种情况下)在其内部创建类实例没有任何意义。如果应将genItem用作项目的容器/存储库,则应在main.cpp(或负责此对象生命周期的任何人)中实例化它,并在其中使用它。打印说明看起来也像是在与编译器战斗时留下的硬核调试代码。
  • 您的代码是可恢复的,但是需要很多工作,我将留给您。进一步了解语法/实现问题。

  • 语法/实现问题
  • 您分配对象并将其保留:用Java或C#编写后,您似乎转向了C++。例如:
    int main()
    {   
        genItem *findItem = new genItem;
    
        int d2 = 0;
        int s2 = 0;
    
        findItem ->generate_item(d2, s2);
    
        cout << "\t"; system("pause");
        return 0;
    }
    

    您实例化genItem,将指向其实例的指针存储在findItem变量中,但只需保留它为即可。以这种方式离开的 Activity 对象被认为是内存泄漏:没有人会为您释放该内存,该对象将一直保持 Activity 状态,直到您的程序终止,即使您不再需要它。注意,您在许多地方都编写了这样的代码。
  • 命名尚不清楚。什么是d2s2?为什么是ds?为什么是2?这段时间磁盘空间非常便宜,没有理由将变量名保持简短和非描述性。给它们起适当的名称(我猜想,在本例中,应将其命名为:newDamagenewStability或类似的
  • 您使IMO的代码复杂化了。这个循环:
    item *genItem::Retrieve(int position)
    {
        item *current = Head;
        for (int i = count() -1; i > position && current != NULL; i--)
        {
            current = current -> Next;
        }
        return current;
    }
    

    可以编写如下(例如):
    item *genItem::Retrieve(int position)
    {
        item * result = Head;
        while (result != nullptr && position > 0)
        {
            result = result->Next;
            position--;
        }
    
        return result;
    }
    

    第二个版本的功能相同(实际上,与您的方法相反,它可以正常工作),并且比第一个版本的可读性更好。
  • 不要用C编写:
    genItem::~genItem(void)
    

    它是有效的C++,但是首选版本是:
    getItem::~getItem()
    
  • 尝试不使用特定于平台的解决方案,例如:
    系统(“暂停”);
    您的程序可能不被允许运行外部命令或程序,并且将崩溃—尽管事实上,您为此类简单任务运行了外部命令。
    如果要停止程序退出,请使用其他解决方案,例如getchar(或查询SO,如何停止程序立即退出)。

  • 简单的例子

    这是一个示例,您的问题可能如何轻松解决了:
    #include <stdio.h>
    #include <string>
    #include <vector>
    #include <iostream>
    
    class Item
    {
    public:
        std::string Name;
        int Damage;
        int Stability;
    
        Item(std::string newName, int newDamage, int newStability)
            : Name(newName), Damage(newDamage), Stability(newStability)
        {
    
        }
    };
    
    class ItemRepository
    {
    private:
        std::vector<Item> items;
    
    public:
        ItemRepository()
        {
            Item item1("Mushroom", 10, 20);
            items.push_back(item1);
            Item item2("Rock", 100, 30);
            items.push_back(item2);
            Item item3("Piece of paper", 5, 2);
            items.push_back(item3);
        }
    
        const Item & GetRandomItem()
        {
            int index = rand() % items.size();
            return items[index];
        }
    };
    
    int main()
    {   
        ItemRepository itemRepo;
    
        for (int i = 0; i < 10; i++)
        {
            const Item & item = itemRepo.GetRandomItem();
    
            std::cout << item.Name << ", Damage: " << 
                item.Damage << ", Stability: " << 
                item.Stability << "\n";
        }
    
        getchar();
    }
    

    关于c++ - C++如何从链表中选择随机项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17141468/

    相关文章:

    有人可以解释一下为什么我的程序崩溃吗?

    c - 由于在 C 中打开新文件而导致数据损坏

    javascript - 跳过 Javascript 数组中的空格

    c++ - eventfd_read/write 与 sem_wait/post

    c++ - 在 C++ (VC++ 2010 Express) 上,双线程应用程序比单线程应用程序慢。怎么解决?

    c++ - visual c++中的strtok问题

    java - 可在 for 循环内运行

    c++ - Mix_PlayMusic 导致内存损坏

    c++ - C - 将指针转换为指向 void 的指针

    c++ - 添加一个 For 循环