custom vector class
Aug 31, 2010 at 8:43pm UTC
so i want to make my own vector class with functions that i use regularly like writing the array, inserting an element, sorting .. that sort of stuff.
and i was thinking i would have a public variable a[NMAX] that would be the array itself. I thought of passing the array`s length as a parameter for the constructor but I don't think i`m doing it right.
main
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <iostream>
#include <vector.h>
using namespace std;
int main()
{
vector v(10);
for (int i=0; i<10; i++)
cout << v.a[i] << " " ;
return 0;
}
vector.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#ifndef VECTOR_H
#define VECTOR_H
class vector
{
public :
vector(int n);
virtual ~vector();
int NMAX;
int a[NMAX];
protected :
private :
};
#endif // VECTOR_H
vector.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include "vector.h"
#include <iostream>
using namespace std;
vector::vector(int n)
{
//ctor
NMAX = n;
}
vector::~vector()
{
//dtor
}
The error I get is : invalid use of non-static data member vector::NMAX.
Do I need some pointers to get the job done ? Please help me out :)
Aug 31, 2010 at 9:01pm UTC
Sep 1, 2010 at 1:52pm UTC
thanks, that worked :D
how do i add more elements ?
Sep 1, 2010 at 8:05pm UTC
allocate a new array, copy each element from the old to the new array, free the old array
Sep 1, 2010 at 8:22pm UTC
brilliant . thanks :)
Sep 1, 2010 at 9:14pm UTC
Brilliant, yet horribly slow. I recommend using a regular vector for things like this (general purpose usage).
Sep 3, 2010 at 12:45pm UTC
Kyon wrote:Brilliant, yet horribly slow. I recommend using a regular vector for things like this (general purpose usage).
And how do you think a regular vector does the resizing?
Topic archived. No new replies allowed.