Очень близко .. Вы пропустили одну крошечную деталь ...
Если вы хотите использовать указатели, вы можете сделать что-то вроде этого
void MyVector::push_back(int x)
{
if (size() == 0)
{
reserve(1);
}
else if (size() == capacity())
{
reserve(capacity() * 2);
arr[size() + 1] = x;
sz++;
}
}
Использование методов, определенных в классе, для определения следующего значения для записи arr
Мне удалось его скомпилировать, используя следующий код для push_back
и reserve()
void MyVector::push_back(int x)
{
if (sz == 0)
{
reserve(1);
}
else if(sz == space)
{
reserve(2 * space);
arr[sz+1] = x;
}
sz++;
}
void MyVector::reserve(int n)
{
int *temp = new int[n];
for (int i=0; i<size(); i++) { // copy the old arr to the new 'temp' one
temp[i] = arr[i];
}
arr = temp;
space = n;
}
Выше я просто создаю *temp
как new int[n]
и затем устанавливаю arr в temp, где n равно новому максимальному размеру списка arr
Я также удалил оба цикла for, поскольку они приводили к возникновению бесконечного цикла
EDIT
#include "MyVector.h"
#include <iostream>
#include <vector>
/* This is whats called a constructor. All of the things entered here will be run at the very start when the object is created */
MyVector::MyVector() {
sz = 0; // set the Integer with the name 'sz' to '0'
space = 0; // set the Integer with the name 'space' to '0'
arr = nullptr; /* set the List of Integers named 'arr' to 'unassigned' */
}
/* this is a separate constructor which allows for this same object to be created with the size and space parameters set to 'n' instead of '0' */
MyVector::MyVector(int n) {
sz = n;
space = n;
arr = new int [n] {0};
}
/* here is a typed method. Typed methods are used to return different
Integers, Booleans, Double, Arrays, or Even Objects such as MyVector.
*/
/* The type is specified first , in this case it is 'int'
* Next, the class that will have this method (in this case 'MyVector')
* Next, the actual method name (in this case 'get')
* and Finally the part inside of the parenthesis is the parameters for this method (int i) which means that whenever you attempt to use this method in the program, you have to include an Integer Object (or a number will work for Integers since its a simple type)
* Essentially this adds the ability to just type in `get(5)` and return the 5th item in the list (array) named 'arr'
*/
int MyVector::get(int i) const {
return arr[i]; /* return is how you essentially specify the response to send and 'i' is the parameter of type 'int' while the brackets [] are for telling the computer which entry from 'arr' to pull */
}
/* here is a method with type 'void' which means that it does not return anything, it only performs operations then finishes */
/* this method (command) can be sent by simply typing */
/* set(5, 3) and the 5th item in the array list will be set to '3'
*/
/* so If i typed this in:
set(1, 5); // set the first item to '5'
set(2, 4); // set the 2nd item to '4'
set(3, 3); // ...
set(4, 2); // ....
set(5, 1); // set the 5th item to '1'
Then the final arr list would be this:
arr = [ 5, 4, 3, 2, 1 ]
*/
void MyVector::set(int i, int x) {
arr[i] = x;
}
// size() is a typed method that returns whatever 'sz' is set to
int MyVector::size() {
return sz;
}
// capacity() is a typed method that returns whatever 'space' is set
// to
int MyVector::capacity() {
return space;
}
// this is the new code I wrote that uses the built-in tools
// to add a new element to the list
// push back is a short way of saying 'add an item to the end of a list' (its programmer lingo I suppose)
/* here is a non-typed method, so it doesnt return anything.. just performs an operation */
void MyVector::push_back(int x)
{
if (size() == 0) // first check if the result of the size() method is 0
{
reserve(1); // if it is '0', then we run the non-typed function 'reserve(1)'
}
else if (size() == capacity()) // if the size() method equals the result of capacity() then..
{
reserve(capacity() * 2); // add additional space to the reserved capacity of the 'arr' list so we can add more items
arr[size() + 1] = x; // now that there is more space, we can set the next item which is 1 more than the current size of arr to whatever we specified as 'x' in the parameter for 'push_back'
sz++; // finally we increase 'sz' by 1 so that the size() method will return how many items are in the array 'arr'
}
}
// here is the new reserve function that I wrote to properly increase the capacity of 'arr'
void MyVector::reserve(int n)
{
int *temp = new int[n]; // create a new blank array with a capacity of 'n'
for (int i=0; i<size(); i++) { // copy the old arr to the new 'temp' one
temp[i] = arr[i];
}
arr = temp; // replace the 'arr' array with our new 'temp' one
space = n; // set the 'space' integer to whatever we specified when we did 'reserve(n)'
}