删除数组中的对象,并通过让其他数组对象相应地向左移动来摆脱空数组空间
Deleting an object in an array, and getting rid of the empty array space by having the other array objects move to the left accordingly
我对c++编码相当陌生,我正在为我正在开发的文本RPG开发菜单系统。您可以查看统计信息、查看库存、查看物品统计信息和丢弃物品。但是,在丢弃物品后,丢弃的物品所在的插槽仍然是空的,并且在游戏中,丢弃对象 2 是没有意义的,然后对象编号 3 仍然是对象 3。对象 3 应变为 2。所以我想知道如何使用我当前的代码来做到这一点。
#include <iostream>
#include <string>
using namespace std;
bool running = 1;
void titleFunc();
void newGameFunc();
void menuFuncNav();
void menuFuncInfo();
void menuFuncItems();
string itemNames[] = {"Iron Short Sword", "Iron Long Sword", "Iron Two-Handed Sword", "Iron War Hammer", "Iron Mace", "Iron Dagger", "Wooden Staff", "Wooden Shield", "Oak Shortbow", "Oak Longbow", "Oak Crossbow", "Hard Leather Chest-Piece", "Hard Leather Leggings", "Soft Leather Chest-Piece", "Soft Leather Leggings", "Cloak"};
short playerItemCount = 0;
int userInput = 0;
int talkInput = 0;
int playerInfo[3];
int playerLocation = 0;
const int MAX_ITEMS = 100;
int playerItems[MAX_ITEMS][11];
void menuFuncItems()
{
int i = 0;
for( int i = 0; i < playerItemCount; i++ )
{
cout << i+1 << ": ";
cout << itemNames[playerItems[i][0]];
cout << endl;
}
cin >> i;
if( playerItems[i - 1][1] == 1 )
{
cout << "Press 1 to view stats." << endl;
cout << "Press 2 to equip." << endl;
cout << "Press 3 to discard." << endl;
cin >> userInput;
cout << endl;
if( userInput == 1 )
{
cout << "Name: " << itemNames[playerItems[i - 1][0]] << endl;
cout << "Physical Attack:" << playerItems[i - 1][2] << endl;
}
else if( userInput == 2 )
{
}
else
{
playerItems[i - 1][0]--;
playerItems[i - 1][0]--;
cout << "Item discarded." << endl;
}
}
因此,在此代码中,玩家丢弃第一个物品栏栏中的物品。
- 铁长剑
- 木盾
- 硬质皮革胸件
- 硬皮紧身裤
第 1 项后,应变为:
- 木盾
- 硬质皮革胸件
- 硬皮紧身裤
对不起,如果我在帖子中做错了什么。这是我在这个网站上的第一篇文章。:)谢谢。
例如,
您可以执行以下操作
for ( int ( *p )[11] = playerItems + i; p != playerItems + playerItemCount; ++p )
{
std::copy( *p, *p + 11, *( p - 1 ) );
}
--playerItemCount;
如果替换
int playerItems[MAX_ITEMS][11];
跟
std::vector<int> playerItems; // assuming you store all the items for a given player here
或
std::vector<std::vector<int>> playerItems; // if you want the 2D array for whatever implementation you have
然后,擦除元素就像调用playerItems.erase(it);
一样简单(其中it
是一个迭代器"指向"要删除的元素。
或者,如果您想要更快的插入/删除(但更慢的随机访问),您可以使用 std::list
。 如果你真的想玩得开心,你可以将它们存储在一个std::map
中,并将项目的名称作为键(而不是使用索引在另一个数组中对项目名称字符串进行)。
相关文章:
- 销毁C++中动态分配的内存(数组对象)
- 数组对象的生存期是否在重用其元素存储时结束?
- 为什么顶点数组对象会导致错误?
- 具有纯虚函数和指针数组对象类型的父类的指针数组
- 这是使用构造函数初始化数组对象的最佳方法吗?
- OpenGL 顶点数组对象与 tinyobjloader
- 将数组/对象/结构列表从C#库中传递给C MFC应用程序
- C++ RapidJson 帮助反序列化数组对象
- ptrdiff_t可以表示指向同一数组对象元素的指针的所有减法吗?
- 检查成员函数是否返回临时对象或数组对象
- 为什么 std::variant 不能容纳数组对象类型,而联合可以?
- 当数组对象以函数参数传递时,为什么复制构造函数会自称
- 如何使用箭头指针打印出一类数组对象,这些对象中有多个分数
- C++17 std::shared_ptr<> 类数组对象的重载运算符 []
- 添加两个具有运算符重载的数组对象,从而导致分段错误
- opengl:两个不同的矢量可以绑定到同一个顶点数组对象吗
- 使用相同的数据填充数组对象或使用指针
- 方法用于最快的分配,并且不需要将动态大小的数组对象作为局部变量
- 如何将2d数组对象传递给c++中的函数
- ReferenceTable溢出(jni-android),数组对象释放