0

I have been making a custom vector class, however I have been bumping into a problem. The problem being that my vector just won't resize, the size stays 0. Anyone know what the problem is?

Thanks in advance!

void resize(const int newSize) {
            // If size is zero, give error
            if (newSize < 0) {
                throw std::out_of_range("Vector");
            }
            // If the given size is smaller than the size that it is now, just ignore
            else if (newSize < capacity) {
                return;
            } 
            // Else, make a new array and copy everything over
            T* newArr = new T[newSize];
            for (int i = 0; i < capacity; i++) {
                newArr[i] = data[i];
            }
            delete[] data;
            capacity = newSize;
            data = newArr;
        }

EDIT 1: Here is the push_back function where resize is needed:

template <typename T> void pushBack(Vector<T>& vector, T& value){
    unsigned int oldSize = vector.size();
    vector.resize(oldSize+1);
    vector.at(oldSize) = value;
}

EDIT 2: Here are the vector deffinitions:

        Vector(const int newSize) {
            if (newSize < 0) {
                throw std::out_of_range("Vector");
            }
            data = new T[newSize];
            capacity = newSize;
            actualSize = 0;
        }
11
  • 2
    Do you differentiate capacity and size? Commented Jan 27, 2022 at 13:46
  • 3
    Please show a minimal reproducible example. Sidenote: If you don't want the size to become negative you could also use an unsigned integer type instead throwing exceptions. Commented Jan 27, 2022 at 13:47
  • 2
    Minimal reproducible exemple should allow us to copy paste your code and compile it. As-is, there are missing stuff, a minimal class Vector (members + constructors (copy/move might be deleted)). Commented Jan 27, 2022 at 13:53
  • 1
    std::vector differentiate size (current number of elements), and capacity (max number of element without reallocations). Showing Vector definition would answer that question. Commented Jan 27, 2022 at 13:54
  • 4
    Can you answer the following question: can everyone else in the world take what you've shown in the question, cut/paste exactly as shown into an empty file, compile, then run and reproduce your problem? Of course, at this time the answer would be "no". So, this is still not a minimal reproducible example. And until you do show a minimal reproducible example, it is unlikely that anyone will be able to tell you what the problem is, but only make random guesses. Commented Jan 27, 2022 at 13:58

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.