Click here to Skip to main content
15,892,480 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hey,
I am having some problem with the following code (Initilization of pointer array).


template <class elementtype="">

class MyVector
{
public:
MyVector(int TotalEntries);
~MyVector();
bool Add(MyVector &a,MyVector *res);

private:
elementType *Arr;
int totalElements;

};

bool MyVector<int>::Add( MyVector &a,MyVector *res)
{
if( totalElements == a.GetTotalEntries() )
{
//How can I initialize it??
res = new elementType [ totalElements + 1 ];
}
}
Posted
Comments
Sergey Alexandrovich Kryukov 5-Feb-13 15:49pm    
Where is a template? (Probably it was hidden because you've forgotten to escape HTML characters with entities).
—SA

1 solution

I think there's some misunderstanding of C++ concepts here. Your Add member function doesn't need the a parameter. It's already a member function meaning it can only be called on an instance of MyVector. You don't need to return the vector after you add to it either so res is not needed.
I'm sat looking at a class right now that is very similar
template < typename T >
class CPodVector
{
...
protected:

T* m_pData;
unsigned int m_Length;
unsigned int m_Capacity;
};


To make use of this I would do something like:
CPodVector< double > APodVector;
double dTest = 3.14159265;
unsigned long ulIndex = 0;
bool bResult = APodVector.insert( 0, dTest );


The two CPodVector functions that get called on the APodVector instance would be the contructor and the insert function which are part of the ... above and go something like.

//constructor
inline CPodVector() : m_pData(0), m_Length(0), m_Capacity(0)
{
}


and

//insert
bool insert( unsigned long ulIndex, const T& item )
{
  if( m_Length == m_Capacity && !grow())
  {
    return false;
  }

  T* dst = m_pData + ulIndex;
  memmove( dst + 1, dst, m_Length - ulIndex );
  memcpy( dst, &item, sizeof(T) );
  m_Length++;
  return true;
}


Of course this is a snippet from a specialist container, in general you should be using std::vector which is thoroughly tested and reliable and has good performance and documentation.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900