STL vector Simulation Implementation modified version

Source: Internet
Author: User

// Iterator. cpp: defines the entry point for the console application.

//

 

# Include "stdafx. H"

 

# Include <iostream>

# Include <New>

 

Using namespace STD;

 

Template <class T>

Class iterator

{

Public:

Iterator ()

: M_pdata (null) //, m_npos (0)

, M_nsize (0), m_nlen (0)

{

}

 

Virtual ~ Iterator ()

{

If (null! = M_pdata)

{

Delete [] m_pdata;

M_pdata = NULL;

}

}

 

Public:

Virtual T * begin () = 0;

Virtual T * end () = 0;

 

Protected:

// Int m_npos;

Int m_nsize;

Int m_nlen;

T * m_pdata;

};

 

Template <class T>

Class cmyvector: Public iterator <t>

{

Public:

Typedef T * iterator;

 

Public:

Cmyvector (INT nsize = 10)

{

If (nsize <= 0)

{

Nsize = 10;

}

 

M_nsize = nsize;

M_pdata = new T [m_nsize];

}

 

~ Cmyvector ()

{

}

 

Public:

Int length () const

{

Return m_nlen;

}

 

Bool push_back (t obj)

{

If (m_nlen> = m_nsize)

{

// Get more memory

Int nsize = m_nsize * 2 + 1;

 

T * ptemp = new (nothrow) T [nsize];

If (! Ptemp)

{

Return false;

}

 

// Memset (ptemp, 0, sizeof (t) * m_nsize );

Memcpy (ptemp, m_pdata, sizeof (t) * m_nlen );

 

Delete [] m_pdata;

M_pdata = ptemp;

M_nsize = nsize;

}

 

Memcpy (m_pdata + m_nlen, & OBJ, sizeof (OBJ ));

M_nlen ++;

 

Return true;

}

 

Public:

Virtual T * end ()

{

Return m_pdata + m_nlen;

}

 

Virtual T * begin ()

{

// M_npos = 0;

Return m_pdata;

}

};

 

Int _ tmain (INT argc, _ tchar * argv [])

{

Cmyvector <int> vtdata;

Cmyvector <int >:: iterator it;

 

For (INT I = 0; I <30; I ++)

{

Vtdata. push_back (I );

// Cout <"nlen =" <vtdata. Length () <Endl;

}

 

Cout <"Vector Data:" <Endl;

For (IT = vtdata. Begin (); it! = Vtdata. End (); It ++)

{

Cout <* It <"/t ";

}

Cout <Endl;

 

Return 0;

}

 

 

Referenced in: http://blog.csdn.net/andylin02/archive/2008/11/27/3392746.aspx

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.