如何动态分配我的数组,重新分配给两次,等等

How do I dynamically allocate my array, reallocate to twice, etc.?

本文关键字:等等 两次 分配 动态分配 数组 新分配 我的      更新时间:2023-10-16

我应该创建一个具有以下行为的成员函数:虚空增长((

  • 如果数组为空(即num_elements_为 0,data_为 nullptr(,请将num_elements_设置为 2,并将data_动态分配为大小为 2。
  • 否则,使用两倍的num_elements_和内部存储的正确密钥重新分配data_,注意正确管理动态分配的内存

我不确定如何动态地将data_分配为大小 2 和第二个项目符号。这让我非常困惑。

#pragma once
#include<iostream>
using std::cout; using std::endl; using std::boolalpha; using std::ostream;
#include<initializer_list>
using std::initializer_list;
#include <algorithm> 
using std::max; using std::copy; using std::swap; 
#include <utility> 
using std::make_pair; using std::pair; 
#include <stdexcept> 
using std::runtime_error; 
#include<vector>
using std::vector;
const static size_t element_array_size = 5;
template<typename K, typename V>
struct Element{
public:
  K key_;
  V values_[element_array_size];//capacity of values
  size_t count_ = 0; //number of values filling values_
  Element()=default;
  Element(K, initializer_list<V>);
  bool operator==(const Element&)const;
  bool operator<(const K&) const; 
  friend ostream& operator<<(ostream& os, const Element& ele){//output element ele
        os<<ele.key_<<":";//display key
        std::copy(ele.values_,(ele.values_+ele.count_-1),std::ostream_iterator<V>(os,","));//display values
        os<<ele.values_[ele.count_-1];
return os;
};//of friend function
};
//count_ and num_keys_ should never be greater than the size or num_elements_
//Code for Element functions goes here
template<typename K, typename V> 
class MVM{
public:
  Element<K, V> *data_ = nullptr;
  size_t num_keys_ = 0; 
  size_t num_elements_ = 0; //capacity
  Element<K, V> *find_key(K);
  size_t find_value(V, K*&);
  void grow(); 
public:
  MVM()=default;
  MVM(initializer_list<Element<K,V>>);
  MVM(const MVM&); 
  ~MVM() {delete[] data_;} 
  size_t size();
  bool add(K,V);  
  bool remove_key(K);
  size_t remove_value(V, K*&);
  friend ostream& operator<<(ostream& oss, const MVM& mv){
    //Code for the ostream operator goes here
    std::copy(mv.data_,(mv.data_+mv.num_keys_-1),std::ostream_iterator<Element<K,V>>(oss," "));//copy elements with spaces in between to ostream oss
    oss<<mv.data_[mv.num_keys_-1];
return oss;
  }//of friend function
};
...

如果您使用的是向量,则可以使用以下方法创建更大的向量:

vector<string> Wibble;
Wibble.resize(10);
...
// or:
...
Wibble.push_back("hello");
Wibble.push_back("world");

或者,如果你使用的是 C,你可以走 malloc 路线,只要你记得事后释放:

char *Data=(char *)malloc(10*sizeof(char));
...
Data=(char *)realloc(Data,20*sizeof(char));
...
free(Data);

你不能做的是把一些静态大小的东西放在一个堆栈上,然后改变你的想法:

char Data[10];

将始终为 10 码,任何更改尺寸的尝试都会给您带来问题。