vector的基本操作实现

/***Dsexceptions.h代码***/

#ifndef DS_EXCEPTIONS_H
#define DS_EXCEPTIONS_H

class UnderflowException { };
class IllegalArgumentException { };
class ArrayIndexOutOfBoundsException { };
class IteratorOutOfBoundsException { };
class IteratorMismatchException { };
class IteratorUninitializedException { };

#endif
/***Vector.h代码***/

#ifndef VECTOR_H
#define VECTOR_H
#include <cstdio>
#include "dsexceptions.h"

template <typename Object>
class Vector
{
  public:
    explicit Vector( int initSize = 0 )
      : theSize( initSize ), theCapacity( initSize + SPARE_CAPACITY ), currentIndex(0)
      { objects = new Object[ theCapacity ]; }
    Vector( const Vector & rhs ) : objects( NULL )
      { operator=( rhs ); }
    ~Vector( )
      { delete [ ] objects; }

    bool empty( ) const
      { return size( ) == 0; }
    int size( ) const
      { return theSize; }
    int capacity( ) const
      { return theCapacity; }

		//操作符[]重载
    Object & operator[]( int index )
    {
                                                     #ifndef NO_CHECK
        if( index < 0 || index >= size( ) )
            throw ArrayIndexOutOfBoundsException( );
                                                     #endif
        return objects[ index ];
    }
		//const操作符[]重载
    const Object & operator[]( int index ) const
    {
                                                     #ifndef NO_CHECK
        if( index < 0 || index >= size( ) )
            throw ArrayIndexOutOfBoundsException( );
                                                     #endif
        return objects[ index ];
    }
		//操作符=重载,实现对象复制
    const Vector & operator= ( const Vector & rhs )
    {
        if( this != &rhs )
        {
            delete [ ] objects;
            theSize = rhs.size( );
            theCapacity = rhs.theCapacity;

            objects = new Object[ capacity( ) ];
            for( int k = 0; k < size( ); k++ )
                objects[ k ] = rhs.objects[ k ];
        }
        return *this;
    }
		//重新设置vector尺寸(两倍)
    void resize( int newSize )
    {
        if( newSize > theCapacity )
            reserve( newSize * 2 );
        theSize = newSize;
    }
		//设置vector尺寸(修改大小,并拷贝所有元素到新的数组,并销毁原来的数组)
    void reserve( int newCapacity )
    {
        Object *oldArray = objects;
    		//1.重设size,capacity
        int numToCopy = newCapacity < theSize ? newCapacity : theSize;
        //capacity是在size的基础上加一个常数
        newCapacity += SPARE_CAPACITY;
    		//2.建立新的数组,并拷贝元素到新数组
        objects = new Object[ newCapacity ];
        for( int k = 0; k < numToCopy; k++ )
            objects[ k ] = oldArray[ k ];
    
        theSize = numToCopy;
        theCapacity = newCapacity;
    		//删除原来的数组
        delete [ ] oldArray;
    }

      // Stacky stuff
    //放置元素,一旦容量达到最大就重置大小
    void push_back( const Object & x )
    {
        if( theSize == theCapacity )
            reserve( 2 * theCapacity + 1 );
        objects[ theSize++ ] = x;
    }
		//删除最后元素
    void pop_back( )
    {
        if( empty( ) )
            throw UnderflowException( );
        theSize--;
    }
		//最后元素
    const Object & back ( ) const
    {
        if( empty( ) )
            throw UnderflowException( );
        return objects[ theSize - 1 ];
    }
    


		//为了遍历vector中的元素,实现一个iterator迭代器(迭代器其实就是指向数组的指针,并对指针操作进行了封装)
      // Iterator stuff: not bounds checked
    typedef Object * iterator;
    typedef const Object * const_iterator;

    iterator begin( ){
    	currentIndex = 0;
    	return &objects[ currentIndex ]; 
    }
    const_iterator begin( ) const{
    	currentIndex = 0;
    	return &objects[ currentIndex ]; 
    }
    iterator end( ){ 
    	return &objects[size( )]; 
    }
    const_iterator end( ) const{
    	return &objects[size( )]; 
    }
    iterator next(){
    	currentIndex++;
      if( currentIndex < 0 || currentIndex > size( ) )
          throw ArrayIndexOutOfBoundsException( );
    	return &objects[currentIndex];
    }
    //插入操作
    void insert(int position,  const Object & x ){
    	//从这里我们也可以看出,插入操作会导致迭代器失效的原因所在(从新分配了空间,原迭代器变成了悬垂指针)
    	if( theSize == theCapacity )
            reserve( 2 * theCapacity + 1 );
      if(position > theSize || position < 0){
      		throw ArrayIndexOutOfBoundsException( );
      }else{
	      for(int i=theSize-1; i>=position; i--){
	      	objects[i+1] = objects[i];
	      }
	      objects[ position ] = x;
        theSize++;
	    }
    }
    //插入(利用迭代器)
    iterator insert(iterator position, const Object& x ){
    	if( theSize == theCapacity )
            reserve( 2 * theCapacity + 1 );
      if(position<begin() || position>end())
    		throw ArrayIndexOutOfBoundsException( );
    	iterator ite = end();
    	while(ite != position){
    		*ite = *(ite-1);
    		ite--;
    	}
    	*position = x;
    	theSize++;
    	return begin();
    }
    
    //擦除从指定位置起数据
    iterator erase(iterator position){
    	if(position<begin() || position>end())
    		throw ArrayIndexOutOfBoundsException( );
    	while(position != end()){
    		theSize--;
    	}
      return begin();
    }
    //擦除从指定范围内的数据
    iterator erase(iterator first, iterator last){ 
    	if((first < begin() || first>end()) || (last < begin() || last>end()) || first>last)
    		throw ArrayIndexOutOfBoundsException( );
    	if(last == end())	erase(first);
    	//1.先将指定范围内的数据覆盖
    	int i=1;
    	while(first != last+1){
    		*first = *(last+i);
    		first++;
    		theSize--;
    		i++;
    	}
    	//2.将覆盖所用数据剩余部分前移(如1,2,3,4,5,6要删除2,3先用4,5覆盖2,3-->1,4,5,4,5,6-->然后6前移到4的位置-->1,4,5,6)
    	i--;
    	while(last <= end()){
    		last++;
    		*last = *(last+i);
    	}
      return begin();
    }

    bool isEnd(){
    	if(currentIndex < 0 || currentIndex >= size( ))
    		return true;
    	return false;
    }
    //操作符++重载(前增量,++a),注还有后增量的重载差不多,只是Object & operator++(int a)有参数
    Object & operator++()
    {                                         
    		currentIndex++;
        if( currentIndex < 0 || currentIndex > size( ) )
            throw ArrayIndexOutOfBoundsException( );
        return objects[ currentIndex ];
    }
<span style="white-space: pre;">	</span>
    //操作符--重载
    Object & operator--()
    {                                         
    		currentIndex--;
        if( currentIndex < 0 || currentIndex > size( ) )
            throw ArrayIndexOutOfBoundsException( );
        return objects[ currentIndex ];
    }

    enum { SPARE_CAPACITY = 16 };

  private:
    int theSize;
    int theCapacity;
    int currentIndex;//仅用于iterator
    Object * objects;
};

#endif

/***Cpp代码***/

#include "vector.h"
#include <iostream>
using namespace std;

int main( )
{
    Vector<int> v;
    

    for( int i = 0; i < 10; i++ )
        v.push_back( i );

    for( int i = 0; i < 10; i++ )
        cout << v[ i ] << " ";
    
  //利用操作符--输出
   Vector<int>::iterator t = v.end()-1;//注意end()返回的是最后元素之后的位置
  	cout<<endl;
  	for(; t >= v.begin(); t--){
  		cout<< *t <<" ";
  	}  

    cout<<endl;
    Vector<int>::iterator k = v.begin();
    while(!v.isEnd()){
    	cout<< *k <<" ";
    	k = v.next();
    }
 
		Vector<int>::iterator m = v.begin()+6;
		//m = v.erase(m);//正确用法
		v.erase(m);	//这样是错误的,会使当前迭代器m失效,必须返回新的迭代器,像上面那样用
    cout<<"\nerase:"<<*m<<endl;
    
  	for(m=v.begin(); m != v.end(); ){
  		cout<< *m <<" ";
  		m = v.next();
  	}


		Vector<int>::iterator mm = v.begin()+2;
		mm = v.insert(mm, 5);
  	cout<<endl;
  	for(; mm != v.end(); ++mm){
  		cout<< *mm <<" ";
  	}
  	

    return 0;
}


转载于:https://www.cnblogs.com/Vulkan/archive/2012/09/19/7530263.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
matrix.h: Simple matrix class dsexceptions.h: Simple exception classes Fig01_02.cpp: A simple recursive routine with a test program Fig01_03.cpp: An example of infinite recursion Fig01_04.cpp: Recursive routine to print numbers, with a test program Fig01_05.cpp: Simplest IntCell class, with a test program Fig01_06.cpp: IntCell class with a few extras, with a test program IntCell.h: IntCell class interface (Fig 1.7) IntCell.cpp: IntCell class implementation (Fig 1.8) TestIntCell.cpp: IntCell test program (Fig 1.9) (need to compile IntCell.cpp also) Fig01_10.cpp: Illustration of using the vector class Fig01_11.cpp: Dynamically allocating an IntCell object (lame) BuggyIntCell.cpp: Buggy IntCell class implementation (Figs 1.16 and 1.17) Fig01_18.cpp: IntCell class with pointers and Big Five FindMax.cpp: Function template FindMax (Figs 1.19 and 1.20) Fig01_21.cpp: MemoryCell class template without separation Fig01_25.cpp: Using function objects: Case insensitive string comparison LambdaExample.cpp: (Not in the book): rewriting Fig 1.25 with lambdas MaxSumTest.cpp: Various maximum subsequence sum algorithms Fig02_09.cpp: Test program for binary search Fig02_10.cpp: Euclid's algorithm, with a test program Fig02_11.cpp: Recursive exponentiation algorithm, with a test program RemoveEveryOtherItem.cpp: Remove every other item in a collection Vector.h: Vector class List.h: List class BinarySearchTree.h: Binary search tree TestBinarySearchTree.cpp: Test program for binary search tree AvlTree.h: AVL tree TestAvlTree.cpp: Test program for AVL trees mapDemo.cpp: Map demos WordLadder.cpp: Word Ladder Program and Word Changing Utilities SeparateChaining.h: Header file for separate chaining SeparateChaining.cpp: Implementation for separate chaining TestSeparateChaining.cpp: Test program for separate chaining hash tables (need to compile SeparateChaining.cpp also) QuadraticProbing.h: Header file for quadratic probing hash table QuadraticProbing.cpp: Implementation for quadratic probing hash table TestQuadraticProbing.cpp: Test program for quadratic probing hash tables (need to compile QuadraticProbing.cpp also) CuckooHashTable.h: Header file for cuckoo hash table CuckooHashTable.cpp: Implementation for cuckoo hash table TestCuckooHashTable.cpp: Test program for cuckoo hash tables (need to compile CuckooHashTable.cpp also) CaseInsensitiveHashTable.cpp: Case insensitive hash table from STL (Figure 5.23) BinaryHeap.h: Binary heap TestBinaryHeap.cpp: Test program for binary heaps LeftistHeap.h: Leftist heap TestLeftistHeap.cpp: Test program for leftist heaps BinomialQueue.h: Binomial queue TestBinomialQueue.cpp: Test program for binomial queues TestPQ.cpp: Priority Queue Demo Sort.h: A collection of sorting and selection routines TestSort.cpp: Test program for sorting and selection routines RadixSort.cpp: Radix sorts DisjSets.h: Header file for disjoint sets algorithms DisjSets.cpp: Efficient implementation of disjoint sets algorithm TestFastDisjSets.cpp: Test program for disjoint sets algorithm WordLadder.cpp: Word Ladder Program and Word Changing Utilities Fig10_38.cpp: Simple matrix multiplication algorithm with a test program Fig10_40.cpp: Algorithms to compute Fibonacci numbers Fig10_43.cpp: Inefficient recursive algorithm (see text) Fig10_45.cpp: Better algorithm to replace fig10_43.c (see text) Fig10_46.cpp: Dynamic programming algorithm for optimal chain matrix multiplication, with a test program Fig10_53.cpp: All-pairs algorithm, with a test program Random.h: Header file for random number class Random.cpp: Implementation for random number class TestRandom.cpp: Test program for random number class UniformRandom.h: Random number class using standard library Fig10_63.cpp: Randomized primality testing algorithm, with a test program SplayTree.h: Top-down splay tree TestSplayTree.cpp: Test program for splay trees RedBlackTree.h: Top-down red black tree TestRedBlackTree.cpp: Test program for red black trees Treap.h: Treap TestTreap.cpp: Test program for treap SuffixArray.cpp: Suffix array KdTree.cpp: Implementation and test program for k-d trees PairingHeap.h: Pairing heap TestPairingHeap.cpp: Test program for pairing heaps MemoryCell.h: MemoryCell class interface (Appendix) MemoryCell.cpp: MemoryCell class implementation (Appendix) MemoryCellExpand.cpp: MemoryCell instantiation file (Appendix) TestMemoryCell.cpp: MemoryCell test program (Appendix)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值