custom vector class

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 :)
You can't declare an array with a variable as size, you'll need to allocate your array on the free store
http://www.cplusplus.com/doc/tutorial/dynamic/
thanks, that worked :D

how do i add more elements ?
allocate a new array, copy each element from the old to the new array, free the old array
brilliant . thanks :)
Brilliant, yet horribly slow. I recommend using a regular vector for things like this (general purpose usage).
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.