向数组添加内容
Adding something to an array
我有一个类,其中一个元素属于另一个类,但是一个数组
class B
{
public:
B() //default
{
element = new A [1]; count = 0;
}
A add(A place)
{
A* newArr;
newArr = new A [count+1];
newArr = element;
newArr[count+1] = place;
delete element;
return newArr[count+1];
}
protected:
int count;
A* element;
};
我正在尝试使用动态数组,在添加元素时,我动态创建一个新数组,启动到旧数组的大小加 1,然后将旧数组的元素复制到新数组,然后删除旧数组。但是我不确定如何修改类中已有的数组,如果这有意义(基本上是在我的 add 方法中返回什么(。
在C++中,一旦声明,就没有调整数组大小的概念。动态数组也是如此,一旦分配就无法调整大小。但是,您可以创建一个更大大小的数组,将所有元素从旧数组复制到新数组并删除旧数组。不鼓励这样做,并且不会执行。
使用 std::vector
将允许您随意添加,并且还会跟踪其大小,因此您不需要count
作为类的一部分。
class B
{
// no need to allocate, do add when required i.e. in B::add
B() : count(), elements() { }
A add(A place)
{
// unnecessarily allocate space again
A *new_elements = new A[count + 1];
// do the expensive copy of all the elements
std::copy(elements + 0, elements + count, new_elements);
// put the new, last element in
new_elements[count + 1] = place;
// delete the old array and put the new one in the member pointer
delete [] elements;
elements = new_elements;
// bunp the counter
++count;
return place; //redundant; since it was already passed in by the caller, there's no use in return the same back
}
protected:
size_t count;
A *elements;
};
上面的代码也许可以做你想要的,但强烈建议不要这样做。 使用向量;你的代码将简单地变成
class B
{
// no need of a constructor since the default one given by the compiler will do, as vectors will get initialized properly by default
void Add(A place)
{
elements.push_back(place);
// if you need the count
const size_t count = elements.size();
// do stuff with count here
}
protected:
std::vector<A> elements;
};
一个更彻底的例子是更紧密地模仿std::vector
:
template<typename T>
class B
{
private: // don't put data under a protected access!
std::size_t _capacity;
std::size_t _size;
T* _elements;
public:
B() : _capacity(0), _size(0), _elements(nullptr) {}
// other methods
void add(const T& t)
{
if (_size >= _capacity) // need to resize the array
{
_capacity++; // you can make this better by increasing by several at a time
T* temp = new T[_capacity];
std::copy(_elements, _elements + _size, temp);
delete [] _elements;
_elements = temp;
}
_elements[_size++] = t;
}
};
相关文章:
- 如何将元素添加到数组的线程安全函数?
- C++ 动态数组每次添加时将大小增加 1 - 错误
- 运算符重载 (+),用于添加两个具有 C++ 的数组
- 添加到数组指针
- 将随机生成的数字添加到数组 + 对这些数组求平均值
- 将数组的元素添加到链表中
- 如何在C++中将元素添加到非固定大小的数组中?
- 将在堆栈上声明的元素添加到静态数组
- const_cast静态数组以添加恒常性
- 在 char* 数组中添加两个索引
- c++ 如何在数组的开头添加值并为其编制索引?
- 检查数组中是否有字符串中的值,如果没有,则添加它
- 添加数组特定列的元素
- 添加数组元素:需要左键作为赋值的左操作数
- 添加数组所有元素的 SSE 指令
- 如何添加数组的偶数和奇数之和
- 向std::multimap添加数组值
- 用内部类函数递归地添加数组数
- 使用自增操作符添加数组元素
- 创建一个模板函数,如果数据类型不同,则添加数组的元素