Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

I'm trying to write my own .h file for my vector template. But I hit a dead end at this point. Can someone help me?

I'm trying to write my own .h file for my vector template. But I hit a dead end at this point. Can someone help me?

Edit1: This is where I'm at right now.

Edit2: Only thing i'm stuck at is PopBack

template // Whatever main puts in the <> gets find-replaced to every "T" class Vector { T* mData; int mSize; // Size is how much data. Capacity is how much memory. int mCapacity;// For testing purposes, initialize this to 15. Whenever you allocate new memory, double it.

T mUndefined;// Lots of STL functions say that doing something naughty gets "undefined behavior". It could throw, crash, make you eggs, or return nonsense. // Return this undefined one if anybody ever tries to go out of bounds.

public: Vector()// O(1) { mSize = 0; mData = nullptr; Reserve(15); } // Big 3 ~Vector() { // Free all memory delete[] mData; } Vector(const Vector& tOther) : Vector()// O(n) { mCapacity = tOther.mCapacity; mSize = tOther.mSize; mData = T[mCapacity]; for (int i = 0; i < mSize; i++) { mData[i] = tOther.mData[i]; } } Vector& operator =(const Vector& tRHS)// O(n) { mSize = tRHS.mSize; mCapacity = tRHS.mCapacity; memcpy(mData, tRHS.mData, tRHS.mCapacity); return *this; // This line is weird so I'm just giving it to ya. It's just the definition of an = } void PushBack(const T& tItem)// O(1) { if (mSize >= mCapacity) { Reserve(this->mCapacity * 2); } mData[mSize] = tItem; mSize++; } void PopBack()// O(1) { } T& At(int tWhere)// O(1) { if (tWhere < 0 || tWhere >= mSize) { return mUndefined; } else return mData[tWhere]; } void Clear()// O(1) { mSize = 0; delete[] mData; } int Size()// O(1) { return mSize; } void Reserve(int tCount)// O(n) { if (mData == nullptr) { mData = new T[tCount]; } mCapacity = tCount; T* temp = new T[mCapacity]; memcpy(temp,mData,mSize); delete[] mData; mData = nullptr; mData = temp; } int Capacity()// O(1) { return mCapacity; } };

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

More Books

Students also viewed these Databases questions

Question

Can we invent a drug that will make people tell the truth?

Answered: 1 week ago