gpt4 book ai didi

c++ - 复制指针数组并跳过某些索引

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:32:30 25 4
gpt4 key购买 nike

我正在尝试为使用指针数组存储对象的数组类创建一个删除函数。

所以我得到的是指向像这样声明的对象的指针列表:

objname* list = new objname[100];

注意,它被声明为一个类的成员,我们称它为 myClass。

我想要的是为 myClass 创建一个函数,该函数将索引作为参数,并从该索引的列表中删除对象。这是我所拥有的和我想做的。

void myClass::remove(int index)
{
objname* temp = new objname[listlen]; //creating a temporary list to copy values from the "main" list.

//want to copy elements from 0 to index in "this->list" and store inside temp, then skip one element and copy the rest.

}

可能有更好的方法来获得此功能,如果是的话,我愿意接受建议。

最佳答案

What I want is to make a function to myClass that takes an index as a parameter, and removes the object from list on that index.

您可以使用 std::vector 轻松做到这一点和 std::next :

#include <vector>   // for std::vector
#include <iterator> // for std::next

std::vector<objname> v;

void myClass::remove(int index)
{
v.erase(std::next(v.begin(), index));
}

显然,您应该首先检查 vector 是否足够大以容纳 index

但是,如果您真正想要做的是将一个数组的一部分复制到另一个数组中,那么您可以使用标准库组件轻松地做到这一点:

std::vector<objname> v = ...;
std::vector<objname> temp(v.begin(), std::next(v.begin(), index));

这里,temp 将包含 v 的第一个 index 元素的拷贝。

关于c++ - 复制指针数组并跳过某些索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21565406/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com