my own <vector>

Hello. I would just like to ask for an advise on how can I implement my own vector. I can't imagine doing the dynamic alocation, because I don't know how does the <vector> actually works. Can you give me some advise please or better would be a link, where can I find the implementation of the STL containers. Thanks.
google for template, see http://cplusplus.com/forum/beginner/32647/ :)
The vector class actually looks something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
template <typename T>
class vector
  {
  private:

    size_t _capacity;  // number of allocated cells
    size_t _length;    // number of cells in use
    T*     _cells;     // the cells (dynamically maintained)

  public:

    explicit vector( size_t n, const T& value = T() ):
      _capacity( n ), _length( n ), _cells( n ? (new T[ n ]) : NULL )
      { }

    ...

    ~vector()
      {
      if (_capacity) delete [] _cells;
      }

    ...
  };

The STL has additional stuff to make it more flexible, but what you have there is the basics. You just need to make sure that _length <= _capacity every time you do something. If it isn't, you must allocate a new array space, copy the old values to the new, free the old space, etc.

Hope this helps.
I have a container class I wrote and used with numbers, and it's pretty much what Duoas shows... I added buffer resizing up and down so if you are pushing one by one, then it's no prob. I probably need to do a front buffer too, but that's an extra pointer, but it might be worth it there are a lot of front push operations... Just make sure that when you mess with pointers and such to watch for double deleting (deleting the same space twice) as I had the problem, but it didn't show until I had huge arrays and it would crash at odd times. Make sure you zero (or null) things after you delete them, or if you aren't going to delete them and pass on the pointer, Null it anyway. It's a pain to track down where the pc is deleting a temp pointer that you are already deleting in a ton of code.

You can look at the class I wrote for some simple advice (look for LameUtils) and look at other classes on the net to see what works. Plus what you are going to use the container for makes a difference on how to code it also.
Yes, always assign NULL to things you delete[] or free().

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <cstring>

...

char* s = NULL;

...

s = new char[ 50 ];
strcpy( s, "Hello world!" );
cout << s << endl;

...

delete [] s;
s = NULL;
how are they implement the iterator of the vectors?Thanks
Duoas. Thank you.
Topic archived. No new replies allowed.