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

标签 c++ arrays algorithm

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

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

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/

相关文章:

c++ - 将此枚举传递给 CTOR 有什么问题?

c++ - 在 C++/C 中使用 CURL 发出带有数据文件的 GET HTTP 请求

c++ - 如何将带有双反斜杠的字符串转换为单反斜杠

Delphi SetLength 自定义索引

java - 数字格式异常 : Invalid int: "1"

c++ - "placement new"有什么用途?

c++ - 这会导致内存泄漏吗?

arrays - 如何在 TypeScript 的接口(interface)中定义一个命名的对象数组?

algorithm - 您如何知道在 AVL 树中的何处执行旋转?

javascript - 任意重新排序和排序对象文字的javascript数组