How to realize dynamic sequence Table in C++
This article mainly explains "how to realize the dynamic sequence table of C++". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn "how to realize the dynamic sequence table of C++".
Vector.h
# pragma once # include # include using namespace std;typedef int DataType;class Vector {public: Vector (): _ first (NULL), _ finish (NULL), _ endofstorage (NULL) {} Vector (const Vector& v) {if (v.Size () > 0) {_ first = new DataType [v.Size ()] / only open up the space occupied by the original data and save space memcpy (_ first, v._first, sizeof (DataType) * v.Size ()); if (_ first) {_ finish = _ first + v.Size (); _ endofstorage = _ first + v.Size ();} else {_ first = _ finish = _ endofstorage = NULL } Vector& operator= (Vector& v) {if (this! = & v) {/ traditional writing / / DataType* tmp = new DataType [v.Size ()]; / / memcpy (tmp, _ first, sizeof (DataType) * v.Size ()); / / delete [] _ first; / / _ first = tmp; / / _ finish = _ first + v.Size () / / _ endofstorage = _ first + v.Size (); / / Modern swap (_ first, v._first); swap (_ finish, v._finish); swap (_ endofstorage, v._endofstorage);} return * this;} ~ Vector () {delete [] _ first; _ first = _ finish = _ endofstorage = NULL;} void Print () {DataType* cur = _ first While (cur! = _ finish) {cout _ first);-- _ finish;} void Vector::Insert (size_t pos, DataType x) {assert (pos = (int) pos) {_ first [end + 1] = _ first[ end];-- end;} _ first[ pos] = x; + _ finish;} void Vector::Erase (size_t pos) {assert (pos < Size ()); size_t cur = pos While (cur < Size ()-1) {_ first [cur] = _ first [cur + 1]; + + cur;}-- _ finish;} size_t Vector::Find (DataType x) {DataType* cur = _ first; while (cur! = _ finish) {if (* cur = = x) {return cur-_ first;} + + cur;} return-1;} void TestVector () {Vector v1; v1.PushBack (1) V1.PushBack (2); v1.PushBack (3); v1.PushBack (4); v1.Print (); size_t pos = v1.Find (2); printf ("pos expect 1 last actual% lu", pos); Vector v2 (v1); v2.Insert (0,0); v2.Print (); Vector v3; v3 = v2; v3.Print (); v3.Erase (1); v3.Print ();}
Test.cpp
# include "Vector.h" int main () {cout