I just started to implement a basic vector container in C++. It is far from completion, but it looks like this:
using namespace std;
typedef unsigned long long int bigInt;
namespace stl2{
template<class T>
class vector{
private:
bigInt l;
bigInt cap;
T* arr;
public:
vector(){
cap = 0;
l = 0;
}
~vector(){
if (cap > 0) delete[] arr;
}
vector(bigInt size){
cap = size;
l = size;
arr = new T[size];
}
vector(bigInt size, const T& def) : vector(size){
for (bigInt i = 0; i < size; i++){
arr[i] = def;
}
}
bigInt size(){
return l;
}
bigInt length(){
return l;
}
bigInt capacity(){
return cap;
}
void resize(bigInt size){
if (size < cap) return;
l = size;
cap = size;
}
void push_back(const T& data){
// Check if vector is full
if (l == cap) {
//Copy all elements of this vector to another
if (cap == 0)
cap = 1;
else
cap *= 2;
T* temp = new T[cap];
for (int i = 0; i < l; i++){
temp[i] = arr[i];
}
delete[] arr;
arr = temp;
}
arr[l] = data;
l++;
}
//Operators
T& operator[](bigInt index){
if (index < cap)
return arr[index];
}
};
}
So I have a problem with the [] operator. I know that if the index < capacity, I can return arr[index]. But what do I return if the index is greater than or equal to the capacity? Since I am returning a reference to the element, I cannot return a value.
Aucun commentaire:
Enregistrer un commentaire