I decided one day to create a class in c++ with storage capabilities similar to that of NSMutableArray in objective c (I know vectors are the goto data type for this sort of thing but I made my own anyway). So I made a mutableArray class in c++, and so far it works great. I can add and remove objects, insert them to a specific index if I want, all without having to specify the size of my array.
So my problem is: so far, it can only store objects of type int. Is there any way I can make it so it holds other datatypes without having to create a whole new class for that specific type? I'm not interested in being able to store objects of different datatypes in the same mutableArray, I just want to be able to specify what datatype my mutableArray holds.
My header file:
#define MUTABLEARRAY_H
class mutableArray
{
public:
mutableArray();
virtual ~mutableArray();
void initWithSize(int length);
void initWithArrayThroughIndeces(int nums[], int minimum, int maximum);
void addObject(int number);
void insertObjectAtIndex(int number, int index);
void changeSize(int length);
void removeLastObject();
void removeObjectAtIndex(int index);
int objectAtIndex(int index);
int lastObject();
int firstObject();
int countObjects();
protected:
private:
int *start;
int amount;
};
#endif // MUTABLEARRAY_H
my cpp file:
#include "mutableArray.h"
mutableArray::mutableArray()
{
//ctor
start = new int;
amount = 0;
}
mutableArray::~mutableArray()
{
//dtor
}
void mutableArray::initWithSize(int length){
amount = length;
}
void mutableArray::initWithArrayThroughIndeces(int nums[], int minimum, int maximum){
amount = maximum - minimum;
start = nums + minimum;
}
void mutableArray::addObject(int number){
amount++;
start[amount] = number;
}
void mutableArray::insertObjectAtIndex(int number, int index){
amount++;
int j = 0;
for (int *i = start + amount; i > start; i--){
if (j >= index){
start[j + 1] = *i;
}
j++;
}
start[index] = number;
}
void mutableArray::removeLastObject(){
amount--;
}
void mutableArray::removeObjectAtIndex(int index){
amount--;
int j = 0;
for (int *i = start; i < start + amount; i++){
if (j != index){
start[j] = *i;
j++;
}
}
}
int mutableArray::objectAtIndex(int index){
return start[index];
}
int mutableArray::lastObject(){
return start[amount];
}
int mutableArray::firstObject(){
return *start;
}
int mutableArray::countObjects(){
return amount;
}
So there it is. Any help will be much appreciated.
std::vector
you mentioned). Warning: Template code cannot be split in .h/.cpp files like non-templated code. So you'll either have to move the code in the .cpp back in to the .h or include the .cpp in the .h (at the bottom). You won't break the ODR (one definition rule) because templates are local to the TU (translation unit). You can easily find more info on this on SO. – Borgleader Jul 18 '13 at 6:13