Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C++
Hey,
I am having some problem with the following code (Initilization of pointer array).
 

template
 
class MyVector
{
public:
MyVector(int TotalEntries);
~MyVector();
bool Add(MyVector &a,MyVector *res);
 
private:
elementType *Arr;
int totalElements;
 
};
 
bool MyVector::Add( MyVector &a,MyVector *res)
{
if( totalElements == a.GetTotalEntries() )
{
//How can I initialize it??
res = new elementType [ totalElements + 1 ];
}
}
Posted 5-Feb-13 8:55am
saad_lah1.1K
Comments
Sergey Alexandrovich Kryukov at 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

Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

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.
  Permalink  

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

  Print Answers RSS
0 OriginalGriff 554
1 Gihan Liyanage 338
2 RyanDev 248
3 Sergey Alexandrovich Kryukov 243
4 ChauhanAjay 220
0 Sergey Alexandrovich Kryukov 9,011
1 OriginalGriff 7,941
2 CPallini 2,603
3 Richard MacCutchan 2,121
4 Abhinav S 1,928


Advertise | Privacy | Mobile
Web02 | 2.8.140827.1 | Last Updated 5 Feb 2013
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100