c ++ динамически выделяемый массив с изменяемым размером - PullRequest
0 голосов
/ 06 августа 2020

хорошо, так что в основном да, мне нужна помощь с домашним заданием Я даже не собираюсь l ie lol ^^; так что одно, что нам нужно сделать, это заставить все эти методы работать вместе в гармонии, пока программа компилятора, в которой мы размещаем наши лаборатории, не скажет pass изображение компилятора, показывающее сообщения о прохождении или неудаче

здесь - это еще одно изображение компилятора и то, как он будет показывать успешность или неуспешность на основе результата при запуске

другое изображение компилятора, показывающее успешность или неудачу результата введенных функций, когда он сообщает к ..thing

, поэтому у меня есть следующие вещи, по которым мне нужна помощь, поэтому по умолчанию, поскольку он показывает проход, я считаю, что сделал это правильно, и в этом есть еще кое-что, мне все еще нужна помощь да, и да, я сам прилагал усилия, я просто хорошо, что указатели всегда меня облажали xD, спасибо заранее.

template<typename Type>
class DynArray {

    friend class TestSuite; // Giving access to test code

    Type* mArray;
    unsigned int mSize;
    unsigned int mCapacity;

public:

    // Default constructor
    //      Creates a new object
    // In:  _startingCap        An initial capacity  to start the array at (optional)
    DynArray(unsigned int _startingCap = 0)
    {
    
        
        mArray = new Array[strlen(_startingCap) + 1];
        strcpy_s(mArray, strlen(_startingCap) + 1, _startingCap);

    }
    

    // Destructor
    //      Cleans up all dynamically allocated memory
    ~DynArray()
    {
        delete[] mArray;
    }

    // Copy constructor
    //      Used to initialize one object to another
    // In:  _da             The object to copy from
    DynArray(const DynArray& _da)
    {
        *this = _da;
    }

    // Assignment operator
    //      Used to assign one object to another
    // In:  _da             The object to assign from
    //
    // Return: The invoking object (by reference)
    //      This allows us to daisy-chain
    DynArray& operator=(const DynArray& _da) {
    
    }

    // Overloaded [] operator
    //      Used to access an element in the internal array (read-only)
    // In:  _index          The index to access at
    //
    // Return: The item at the specified index (by reference)
    const Type& operator[](int _index) const 
    {
    
    }

    // Overloaded [] operator
    //      Used to access an element in the internal array (writeable)
    // In:  _index          The index to access at
    //
    // Return: The item at the specified index (by reference)
    Type& operator[](int _index) {
        
    }

    // Get the current number of elements actively being used
    //
    // Return: The current number of elements used
    int Size() const {
        
    }

    // Get the current capacity of the internal array
    //
    // Return: The capacity of the array
    int Capacity() const {
        
    }

    // Clear the class for re-use
    //          Should clean up all dynamic memory and leave the object the same as if the default constructor had been called
    void Clear() {
        
    }

    // Add an item to the end of the array
    //          Should resize the array if needed
    // In:  _data           The item to be added
    void Append(const Type& _data) {
        
    }

    // Resizes the internal array, and copies all data over
    // In: _newCapacity     The new capacity of the array
    //  NOTE:   If 0 is passed, the array should double in size
    //          If _newCapacity < mCapacity, do nothing
    //
    //  SPECIAL CASE: If mCapacity is 0, then it should be set to 1
    void Reserve(unsigned int _newCapacity = 0)
    {
        
        if (_newCapacity < mCapacity)
        {
            continue;
        }
        if (mCapacity = 0)
        {
            mCapacity = 1;
        }
    }

};
#endif

Ответы [ 2 ]

0 голосов
/ 06 августа 2020

вот обновленная версия с реализованными предложениями ^ U ^ шаблонный класс DynArray {

friend class TestSuite; // Giving access to test code

Type* mArray;
unsigned int mSize;
unsigned int mCapacity;

publi c:

// Default constructor
//      Creates a new object
// In:  _startingCap        An initial capacity  to start the array at (optional)
DynArray(unsigned int _startingCap = 0)
{

    
    mArray = new Type[_startingCap];
    mCapacity = _startingCap;
    mSize = 0;

}


// Destructor
//      Cleans up all dynamically allocated memory
~DynArray()
{
    delete[] mArray;
}

// Copy constructor
//      Used to initialize one object to another
// In:  _da             The object to copy from
DynArray(const DynArray& _da)
{
    operator = (_da)
}

// Assignment operator
//      Used to assign one object to another
// In:  _da             The object to assign from
//
// Return: The invoking object (by reference)
//      This allows us to daisy-chain
DynArray& operator=(const DynArray& _da) {

}

// Overloaded [] operator
//      Used to access an element in the internal array (read-only)
// In:  _index          The index to access at
//
// Return: The item at the specified index (by reference)
const Type& operator[](int _index) const 
{

}

// Overloaded [] operator
//      Used to access an element in the internal array (writeable)
// In:  _index          The index to access at
//
// Return: The item at the specified index (by reference)
Type& operator[](int _index) {
    
}

// Get the current number of elements actively being used
//
// Return: The current number of elements used
int Size() const 
{
    return Size;
}

// Get the current capacity of the internal array
//
// Return: The capacity of the array
int Capacity() const {
    
}

// Clear the class for re-use
//          Should clean up all dynamic memory and leave the object the same as if the default constructor had been called
void Clear() {
    
}

// Add an item to the end of the array
//          Should resize the array if needed
// In:  _data           The item to be added
void Append(const Type& _data) {
    
}

// Resizes the internal array, and copies all data over
// In: _newCapacity     The new capacity of the array
//  NOTE:   If 0 is passed, the array should double in size
//          If _newCapacity < mCapacity, do nothing
//
//  SPECIAL CASE: If mCapacity is 0, then it should be set to 1
void Reserve(unsigned int _newCapacity = 0)
{
    
    if (_newCapacity < mCapacity)
    {
        continue;
    }
    if (mCapacity == 0)
    {
        mCapacity = 1;
    }
}

};

0 голосов
/ 06 августа 2020

Давайте исправим тот, который вы пытались сделать. Это иллюстрирует многие ваши недоразумения.

Так что подумайте, что требуется.

  1. Мы должны создать массив с заданной емкостью, что означает выделение заданного числа элементов и присваивая их указателю mArray

  2. Мы должны установить емкость массива равной заданному значению.

  3. После создания размер массивов будет равен нулю, поэтому мы должны установить размер равным нулю.

Собирая все вместе, получаем

DynArray(unsigned int _startingCap = 0)
{
    // allocate memory for the given capacity
    mArray = new Type[_startingCap];
    // set the array capacity to the given value
    mCapacity = _startingCap;
    // set the size to zero
    mSize = 0;
}

Я не знаю, куда начните с вашего кода. Вы явно откуда-то скопировали какой-то строковый код и пытались адаптировать его к новой ситуации. Но этот код не имеет ничего общего со строками, и даже если забыть о разнице между строками и массивами, код, который вы скопировали, делал что-то совершенно другое.

Понимаете ли вы концепции размера и емкости, и разницу между их? Код, который вы написали выше, предполагает, что это не так. Вам действительно нужно будет понять эту концепцию, прежде чем go продолжить.

Размер массива - это количество допустимых элементов в массиве. Достаточно просто.

Емкость массива - это то, сколько памяти он выделил. Массив может иметь большую емкость, чем его размер (но, очевидно, не может быть меньше). Дополнительная емкость позволяет массиву расти (т. Е. Увеличивать его размер) без необходимости перераспределять память, содержащую элементы массива.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...