Как бы я объединил два ArrayList, которые имеют специальный тип? - PullRequest
0 голосов
/ 02 мая 2020

Целью этой части задания является создание специализированных реализаций ArrayList из Addresses или ArrayList<Address>. Мы должны объединить два ArrayList этого типа, но из-за нашего начального кода я немного потерялся в том, с чего начать.

Во-первых, у нас есть шаблонный ArrayList из класса в ArrayList.h вместе с некоторыми функциями для go с этим:

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 в Address.h:

#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 есть функция мы должны реализовать. Указывается, что это «специализация шаблона для ArrayList of Addresses. Это определение объединения, которое будет работать ТОЛЬКО для ArrayList». Моя путаница начинается с этого момента. Функция должна быть реализована в соответствии с чем-то вроде listA.combine(listB), и учитывая этот факт и весь код, уже предоставленный нам, я думаю, что мне нужно использовать указатель this, но то, что я попробовал ниже, привело к сбою и я не знаю куда go отсюда.

// @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];
    }
}

1 Ответ

0 голосов
/ 02 мая 2020

Вы можете просто использовать 'insertEnd ()', как рекомендует NadavS, но если otherList очень длинный, то вы можете в конечном итоге вызвать grow() на insertEnd() несколько раз, что неэффективно. Чтобы оптимизировать это, я думаю, вы можете изменить 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];
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...