Я не могу понять указатели с вектором или массивом - PullRequest
0 голосов
/ 05 мая 2018

У меня проблемы с заданием по информатике. В этом задании мы используем указатели с классами. И это мой первый раз, когда я изучаю указатели, и их очень трудно понять для меня. Я не знаю, правильно ли я делаю или нет, но вот что сказал мой профессор, что мне нужно сделать с помощью функции Push_back. Он сказал, что нам нужно использовать массив, но мы не можем push_back элемент в массив?

Я делаю что-то не так с какой-либо функцией? Или следует предоставить более подробную информацию. Дайте мне знать.

/*Push an element to the end of the array:
        if sz == 0, reserve 1
        else if sz == space, reserve 2 * space
        assign x to the end of the array.
        increment sz*/
void push_back(int x);

#include "MyVector.h"
#include <iostream>
#include <vector>

MyVector::MyVector() {
    sz = 0;
    space = 0;
    arr = nullptr;
}

MyVector::MyVector(int n) {
    sz = n;
    space = n;
    arr = new int [n] {0};
}

int MyVector::get(int i) const {
    return arr[i];
}

void MyVector::set(int i, int x) {
     arr[i] = x;
}

 int MyVector::size() {
    return sz;
}

int MyVector::capacity() {
    return space;
}

void MyVector::push_back(int x) {
    for (int i = 0; i < sz; i++) {
        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 < sz; i++) {
        *(temp + i) = *(arr + i);
        delete[] arr;
        arr = temp;
        space = n;
    }
}

Вот мой .h файл для объявления класса.

#ifndef MyVector_h
#define MyVector_h

#include <iostream>
using namespace std;

class MyVector {
public:
    MyVector();
    MyVector(int n);
    int get(int i) const;
    void set(int i, int x);
    int size();
    int capacity();

    /*Push an element to the end of the array:
     if sz == 0, reserve 1
     else if sz == space, reserve 2 * space
     assign x to the end of the array.
     increment sz*/
    void push_back(int x);
    void reserve(int n);
private:
    int sz;
    int space;
    int *arr;
};

#endif /* MyVector_hpp */

Ответы [ 2 ]

0 голосов
/ 05 мая 2018

Оба ваших push_back и reserver были неправы, они должны быть:

void MyVector::push_back(int x)
{
    if (sz == 0)
        reserve(1);
    else if (sz == space)
        reserve(2 * space);
    arr[sz] = x;
    sz++;
}

void MyVector::reserve(int n)
{
    int *temp = new int[n];
    for (int i = 0; i < sz; i++)
        *(temp + i) = *(arr + i);
    delete[] arr;
    space = n;
    arr = temp;
}
0 голосов
/ 05 мая 2018

Очень близко .. Вы пропустили одну крошечную деталь ...

Если вы хотите использовать указатели, вы можете сделать что-то вроде этого

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)'
}        
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...