Как бы вы вставили число в указанное c место в массиве? - PullRequest
1 голос
/ 26 марта 2020
#include <iostream>

class Vector
{
public:

    int size;
    int* contents;
    int capacity;

    Vector();

    ~Vector();


    void PushFront(int value);

    //void Vector(int initialCapacity);

    void PushBack(int value);


    int& At(int index);


    int& operator[](int index);


    void Clear();


    int Size();


    bool IsEmpty();


    void Resize(int newSize);


    void Reserve(int newCapacity);


    int GetCapacity();


    void EraseAt(int index);


    void Erase(int value);


    int Find(int value);

    bool Contains(int value);

    void Insert(int value, int index);
};

Итак, это объявления функций, которые я использовал для другого файла, они включены для справки.

#pragma once
#include <iostream>
#include <string>
#include "Header.h"


    //double* vPointer;
    double* vPointer;
    int* myArray[];



    Vector::Vector()
    {
        std::cout << "Vector Class Created." << std::endl;
        capacity = 10,
        contents = new int[capacity],
        size = 0;
    }


    Vector::~Vector()  // Deallocates any memory the container needed to allocate
    {
        delete[] vPointer;
        std::cout << "Vector Class Deallocated." << std::endl;

    }


    void Vector::PushFront(int value) // Adds a single value to beginning of the container
    {
        for (int i = 0; i <= size; ++i)
        {

            if (value < vPointer[capacity])
            {
                Reserve(capacity + 1);
            }
            if (i == value)
            {
                std::cout << "testing." << std::endl;
            }
            if (i > value)
            {
                std::cout << "testing (code 2)." << std::endl;
            }
        }
    }

    void Vector::PushBack(int value) // Adds a single value to end of the container
    {
        if (size == capacity)
        {
            Reserve(capacity + 1);
        }
        contents[size] = value;
        size++;
    };

    void Vector::Reserve(int newCapacity) // Allocates room for at least this many values.  Does not shrink the storage
    {
        if (capacity < newCapacity)
        {
            int* newArray = new int[newCapacity];
            for (int i = 0; i < size; i++)
            {
                newArray[i] = contents[i];
            }
            delete[] contents;
            contents = newArray;
            capacity = newCapacity;
        }
    }


    int& Vector::At(int index) // Return a reference to the element at the given index.  If unable, throws an exception.
    {
        return contents[index];
    }

    int& Vector::operator[](int index) // Return a reference to the element at the given index.  If unable, throws an exception.
    {
        std::cout << contents[index] << std::endl;
        return contents[index];
    }

    void Vector::Clear() // Remove all elements from the container
    {
        size = 0;
    }

    int Vector::Size() // Returns the number of elements in this container
    {
        return size;
        std::cout << size;
    }

    bool Vector::IsEmpty() // Returns whether or not the container has any elements
    {
        std::cout << "Container has the following number of elements: " << vPointer << std::endl;
        return vPointer;
    }

    void Vector::Resize(int newSize)  // Adds or removes elements from the end of the container to achieve the given new size
    {
        if (newSize < size)
        {
            size == newSize;

            std::cout << newSize << std::endl;

        }



        else if (newSize > capacity)
        {
            Reserve(newSize);
            size == newSize;
            return;
        }

        else 
        {
            std::cout << "something went wrong! Attempting to ReSize Anyways..." << std::endl;
            size = newSize;

            std::cout << "Vector Resized. newSize = " << newSize << std::endl;

        }


    }

    int Vector::GetCapacity()  // Returns the amount of allocated space
    {
        return capacity;

    }


    void Vector::EraseAt(int index)  // Removes the value at the given index, decreasing the contained size
    {
        for (int i = 0; i < size; i++)
        {
            if (vPointer[i] == index)
            {
                std::cout << "semi-functional." << std::endl;

            }
        }
    }

    void Vector::Erase(int value)  // Removes one value from the container: the first that matches
    {
        for (int i = 0; i < size; i++)
        {
            if (value == vPointer[i])
            {
                vPointer[i] = vPointer[i + 1];
            }
            else
            {
                //cout << "can't erase a value that does not exist." << endl;
                return;
            }
        }
    }


    int Vector::Find(int value)  // Returns the index of the given value, -1 if not found
    {
        for (int i = 0; i < size; i++)
        {
            if (value == vPointer[i])
            {
                std::cout << "Value Found : " << i << std::endl;
                return i;
            }
            else
            {
                return -1;
                std::cout << "Value Not Found" << std::endl;
            }
            if (value != vPointer[i])
            {
                std::cout << "Value Found : " << i << std::endl;
                return i;
            }
        }
    }

    bool Vector::Contains(int value)  // Returns true if this value is in the container
    {
        for (int i = 0; i < size; i++)
        {
            if (value < size)
            {


                std::cout << "The Value " << value << " Is In The Container." << std::endl;
                return value;
                return true;
            }
            else
            {
                std::cout << "The Value Is Not Within The Container." << std::endl;
                return false;
            }
        }

    }
    void Vector::Insert(int value, int index) // Insert the given element at the given position. Position 0 should insert the element at the beginning of the container
    {

    }

Это здесь ^^^ где у меня проблемы. Некоторые вещи, которые я пытаюсь запрограммировать, вообще не хотят работать, и я не могу использовать их, потому что проект состоит в создании «векторного» класса с использованием массивов. Я заблудился о том, как вставить целое число в массив в этом случае, потому что я не могу найти массив, который мы выделили. Учитель говорит, что это здесь, но я не могу назвать это вообще.

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

//using namespace std;

int main(int argc, char* argv[])
{
    Vector myVector;
    std::cout << "Initializing 'Vector' Array..." << std::endl;

    std::cout << " " << std::endl;
    std::cout << "myVector.PushBack():" << std::endl;
    //myVector.PushBack      
    myVector.PushBack(3);
    std::cout << "Should be 3: " << myVector.At(0) << std::endl;

    std::cout << " " << std::endl;
    std::cout << "myVector.Reserve():" << std::endl;
    //myVector.Reserve
    std::cout << "Capacity: " << myVector.capacity << std::endl;
    myVector.Reserve(15);
    std::cout << "Should allocate 5 slots in the array: " << std::endl; 
    std::cout << "New Capacity: " << myVector.capacity << std::endl;

    //myVector.At
    std::cout << " " << std::endl;
    std::cout << "myVector.At():" << std::endl;
    std::cout << "Testing myVector.At(#) with value of 0... : " << myVector.At(0) << std::endl;

    //myVector GetCapacity
    std::cout << " " << std::endl;
    std::cout << "myVector.GetCapacity():" << std::endl;
    myVector.GetCapacity();
    std::cout << "Capacity of Array: " << myVector.capacity << std::endl;

    //myVector.Resize()    -not working- 
    std::cout << " " << std::endl;
    std::cout << "myVector.Resize():" << std::endl;
    std::cout << "Orignal Vector Size: " << myVector.size << std::endl;
    myVector.Resize(12);


    //myVector Clear() + myVector Size()
    std::cout << " " << std::endl;
    std::cout << "myVector Clear() + myVector Size():" << std::endl;
    myVector.Clear();
    std::cout << "clearing myVector... Current Size:" << myVector.Size() << std::endl;

    //myVector IsEmpty()
    std::cout << " " << std::endl;
    std::cout << "myVector.IsEmpty();:" << std::endl;
    myVector.IsEmpty();



    std::cout << " " << std::endl;
    std::cout << "myVector.Operator[]:" << std::endl;
    //myVector.operator[](int index)
    myVector.operator[](3);









    std::cout <<  myVector.Size() << std::endl;
    std::cout << "NEEDS DEBUGGING:" << std::endl;

    //-not working - :

    //myVector Erase        
    std::cout << " " << std::endl;
    std::cout << "myVector.Erase:" << std::endl;   
    myVector.Erase(3);
    std::cout << myVector.Size() << std::endl;
    std::cout << myVector.GetCapacity() << std::endl;


    std::cout << " " << std::endl;
    std::cout << "myVector.EraseAt:" << std::endl;
    //myVector EraseAt         
    myVector.EraseAt(3);


    std::cout << " " << std::endl;
    std::cout << "myVector.Contains:" << std::endl;
    //myVector.Contains()
    myVector.Contains(0);


    std::cout << " " << std::endl;
    std::cout << "myVector.Find:" << std::endl;
    //myVector.Find()
    myVector.Find(0);


    std::cout << " " << std::endl;
    std::cout << "myVector.PushFront():" << std::endl;
    //myVector.PushFront(3); 
    //myVector.PushFront(3);


    std::cout << " " << std::endl;
    std::cout << "myVector.Insert:" << std::endl;
    //myVector.Insert()




    //myVector.~Vector();   THIS FUNCTIONS!
    std::cout << " " << std::endl;
    std::cout << "myVector.~Vector()" << std::endl;
    myVector.~Vector();
    //std::cout << "Memory DeAllocated." << std::endl;
    std::cin.get();
}

Эти части - только я, проверяющие их в основном файле. Несколько вещей помечены как сломанные, потому что они не работают. Я больше сосредоточен на исправлении PushFront и Insert, если кто-нибудь может мне помочь. Я пытался искать в Интернете, но я не могу найти то, что понимаю.

1 Ответ

1 голос
/ 27 марта 2020

Просто нажмите на элемент, а затем поверните его на место

void Vector::Insert(int value, int index) // Insert the given element at the given position. Position 0 should insert the element at the beginning of the container
{
  PushBack(value);
  std::rotate(contents + index, contents + size - 1, contents + size);
}
...