如何组合两个特殊类型的ArrayList



这部分任务的目标是创建AddressesArrayList<Address>ArrayList的专用实现。我们将组合两个这种类型的ArrayList,但我们给定的起始代码让我有点不知道从哪里开始。

首先,我们有一个来自ArrayList.h中类的模板化ArrayList,以及一些与之配套的函数:

template <class T>
class ArrayList {
public:
/**
* @brief Add copy of item to the end of the list, growing internal storage if needed
* @param insertItem Item to duplicate into the list
*/
void insertEnd(const T& insertItem);
/**
* YOU WILL IMPLEMENT IN AddressArrayList.h/cpp
*/
void combine(ArrayList<T>& otherList);
protected:
/**
* @brief Allocate new storage array double old capacity and copy
*          existing items to it.
*/
void grow();
T* list;        ///dynamic array holding stored items
int length;     ///logical length of list - how many items are being stored
int maxSize;    ///size of array used for storage
};
template <class T>
void ArrayList<T>::grow()
{
int newSize = maxSize * 2;
T* tempList = new T[newSize];
for(int i = 0; i < maxSize; i++)
tempList[i] = list[i];
maxSize = newSize;
delete [] list;
list = tempList;
}
template <class T>
void ArrayList<T>::insertEnd(const T& insertItem)
{
if(length == maxSize)
grow();
list[length] = insertItem;
length++;
}

在此之后,我们在Address.h:中定义了Address

#ifndef ADDRESS_H
#define ADDRESS_H
#include <string>
#include <fstream>

struct Address {
std::string first;
std::string last;
std::string streetAddr;
std::string city;
std::string county;
std::string state;
int zipCode;
Address();
//Accepts comma seperated line of text with fields in order of member variables
explicit Address(const std::string& dataLine);
};

最后,在AddressArrayList.cpp中是我们应该实现的功能。它被称为"地址数组列表的模板专用化。这是在定义一个仅适用于数组列表的组合"。我的困惑开始于此。该函数应该按照listA.combine(listB)之类的方法来实现,考虑到这一事实以及已经提供给我们的所有代码,我认为我需要使用this指针,但我在下面尝试的操作导致了失败,我不知道该从哪里开始。

// @brief Move all items from otherList to the end of this List.
// @param otherList List to be combined into this one. It should end up empty.
template <>
void ArrayList<Address>::combine(ArrayList<Address>& otherList) {
grow();
for (int i = 0; i < this->length + otherList.length; i++) {
this->list[i + length] = otherList.list[i];
}
}

您可以按照NadavS的建议简单地使用'insertEnd((',但如果otherList很长,那么您可能会多次被insertEnd()调用grow(),这是低效的。为了优化这一点,我认为您可以修改grow()以只增加一次容量。

template <class T>
void ArrayList<T>::grow(int more=0)
{
int newSize = maxSize + (more > 0 ? more : maxSize);
T* tempList = new T[newSize];
for(int i = 0; i < maxSize; i++)
tempList[i] = list[i];
maxSize = newSize;
delete [] list;
list = tempList;
}
template <>
void ArrayList<Address>::combine(ArrayList<Address>& otherList) {
grow(otherList.length);
for (int i = 0; i < this->length + otherList.length; i++) {
this->list[i + length] = otherList.list[i];
}
}

最新更新