提问人:evanparial 提问时间:9/5/2022 更新时间:9/5/2022 访问量:53
如何使用 c++ 中的 NEW 运算符为完整列表分配更多内存?
How can I allocate more memory to a full list using the NEW operator in c++?
问:
我正在尝试制作带有歌曲的播放列表。我在 c++ 中使用 List 数据结构。我想改进函数 insert(),如果我的列表充满了 100 首歌曲,我可以使用运算符 NEW 为列表分配更多内存。我还必须使用 delete[] 解除分配现有内存。
我不确定如何创建一个新列表并将它们连接在一起。
这是我的 List 类:
#include <string>
#include <iostream>
#include <stdexcept>
using namespace std;
template<class ItemType>
class List
{
private:
static const int CHUNK_SIZE=100;
ItemType *list;
int numItems;
int maxItems;
public:
// default constructor and destructor
List()
{
numItems = 0;
maxItems = CHUNK_SIZE;
list = new ItemType[CHUNK_SIZE];
}
~List()
{
delete[] list;
}
// list member functions
bool isEmpty() const
{
return numItems==0;
}
int getLength() const
{
return numItems;
}
bool insert(int pos, const ItemType& item);
bool remove(int pos);
// clear the list
// clear can simply set numItems to zero. The array list may still contain
// items already inserted into the list, but since numItems is zero, there
// isn't any way to get at them using getEntry() or setEntry()
void clear()
{
numItems = 0;
}
// return entry at postion pos
// throw invalid_argument if pos<1 or pos>getLength()
ItemType getEntry(int pos) const;
// set entry at postion pos to item
// throw invalid_argument if pos<1 or pos>getLength()
// changes whatever is inside the position to that item. swap.
void setEntry(int pos, const ItemType& item);
};
这是我的 insert() 函数:
template<class ItemType>
bool List<ItemType>::insert(int pos, const ItemType& item)
{
bool canAdd;
canAdd = ((pos > 0) && (pos <= numItems + 1) && (numItems < maxItems));
if (canAdd)
{
// first, we have to move everything after our insertion point over one
// position to make room for our new item. start at the back of the list.
// don't forget arrays start at postion zero and our list ADT starts at
// position 1.
for(int i=numItems; i>=pos; i--)
list[i] = list[i-1];
// now put our item at position pos-1
list[pos-1] = item;
numItems++;
}
return canAdd;
}
这是我的 main() 函数:
int main()
{
List<string> songs;
char goAgain = 'y';
int trackNumber;
string trackName;
// Insert some songs into our list
songs.insert(1, "Bohemian Rhaspody");
songs.insert(2, "The Highway Song");
songs.insert(3, "In the Loop");
songs.insert(4, "Lovesong");
songs.insert(5, "Blow The Whistle");
songs.remove(1);
cout << "Welcome! There are " << songs.getLength() << " tracks.\n";
while (goAgain!='n')
{
trackNumber = getTrack();
try
{
trackName = songs.getEntry(trackNumber);
}
catch (invalid_argument arg)
{
cout << arg.what() << endl;
trackName = "No Track";
}
cout << "Your track name is " << trackName << endl;
cout << "Go again? (y/n) ";
cin >> goAgain;
}
cout << "you're ready to rock!\n";
return 0;
}
答: 暂无答案
评论
new
delete
insert