[LC++]STL-like vector, but with domain a ... (b-1)

Mark Phillips mark at austrics.com.au
Tue Jan 8 22:11:31 UTC 2002


Hi,

I am trying to create my own vector class, like the STL one, but 
instead of it having domain 0..size()-1, I wish it to have an
aribrary origin, ie so that it can have domain a() ... b()-1

ie the domain is all i satisfying  a() <= i < b()

I implemented my class as follows:

  template<typename tn> class abVectorTt {
  private:
    vector<tn> vecVt;
    int originVt;
  public:
    int size() const {return vecVt.size();}
    int a() const {return -originVt;}
    int b() const {return vecVt.size()-originVt;}
    tn& operator[](int i) {return vecVt[i-originVt];}
    tn const& operator[](int i) const {return vecVt[i-originVt];}
    void resize(int aAg, int bAg) {originVt=-aAg; vecVt.resize(bAg-aAg);}
    void resize(int aAg, int bAg, tn const& xAg) {
      originVt=-aAg; vecVt.resize(bAg-aAg, xAg);
    }
    abVectorTt(): originVt(0) {}
    abVectorTt(int aAg, int bAg): originVt(-aAg), vecVt(bAg-aAg) {}
    abVectorTt(int aAg, int bAg, tn const& xAg): originVt(-aAg), 
	vecVt(bAg-aAg, xAg) {}
  };

Then all I have to do is

  abVectorTt<int> abvec(-3, 7, 0);

and I have an integer vector with domain -3..7, initialized to 0.

But what if I want a vector of vectors?  Well I do

  abVectorTt<abVectorTt<int> > abvecvec(-3, 7);
  for (int i=-3; i<7; ++i)
    abvecvec[i].resize(-1, 4, 0);

And I should effectively have a two dimension vector with
domain -3..7 by -1..4.  But when I have tried it, it doesn't
work properly!!!

If I go "abvecvec[0].a()"or the like, things are fine.  But if
I go "abvecvec[0][0]" I get a segmentation fault!  If I try to do

  abVectorTt<int> abvec=abvecvec[0];

it seg faults!

I wondered whether it was because I was using the default copy
constructor and default assignment operator.  I thought I wouldn't
need to specially define these, but just in case, I added the 
following:

    tn& operator=(tn const& xAg) {
      if (xAg!=this) {
	originVt=xAg.originVt;
	vecVt=xAg.vecVt;
      }
      return *this;
    }

and

    abVectorTt(abVectorTt<tn> const& xAg): originVt(xAg.originVt), 
        vecVt(xAg.vecVt) {}

Unfortunately it doesn't seem to help.

Can someone please tell me what I'm missing?

Thanks!!!

Mark.



More information about the tuxCPProgramming mailing list