From 207d6fe1e420b1df1c0168e788963efaab61dc6c Mon Sep 17 00:00:00 2001 From: iridiumR Date: Thu, 7 Oct 2021 23:29:11 +0800 Subject: [PATCH] =?UTF-8?q?2=E5=88=9B=E5=BB=BA=E5=A4=B4=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ex2/vector.h | 160 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 160 insertions(+) create mode 100644 ex2/vector.h diff --git a/ex2/vector.h b/ex2/vector.h new file mode 100644 index 0000000..6726dcd --- /dev/null +++ b/ex2/vector.h @@ -0,0 +1,160 @@ +#ifndef _INC_STDIO + #include +#endif + +#ifndef _GLIBCXX_STDLIB_H + #include +#endif + +class Vec +{ +private: + int *v; + int LEN; + int USED; + + void expand(); + + void shrink(); + +public: + Vec(int len); + + int get(int a); + + void put(int a, int value); + + void swap(int a, int b); + + int insert(int locate, int value); + + int del(int locate, int value); + + int find(int value); + + void printall(); + + int getlen(); + + int getused(); +}; + +Vec::Vec(int len) +{ + LEN = len * 2; + v = new int[LEN]; + USED = 9; + + for (int i = 0; i < 10; i++) + v[i] = i + 1; + + for (int i = 0; i < 10; i++) + swap(i, rand() % 10); +} + +int Vec::get(int a) +{ + return v[a]; +} + +void Vec::put(int a, int value) +{ + v[a] = value; +} + +void Vec::swap(int a, int b) +{ + int temp = v[a]; + v[a] = v[b]; + v[b] = temp; +} + +void Vec::expand() +{ + LEN = LEN * 2; + int *p = new int[LEN]; + + for (int i = 0; i <= USED; i++) + p[i] = v[i]; + + delete[] v; + v = p; +} + +void Vec::shrink() +{ + LEN = LEN >> 1; + int *p = new int[LEN]; + + for (int i = 0; i <= USED; i++) + p[i] = v[i]; + + delete[] v; + v = p; +} + +int Vec::insert(int locate, int value) +{ + if (locate < 0 || locate > USED) + return 1; + + USED++; + + if (USED >= LEN) + expand(); + + for (int i = USED; i > locate; i--) + v[i] = v[i - 1]; + + v[locate] = value; + + return 0; +} + +int Vec::del(int locate, int value) +{ + + if (locate < 0 || ((USED - value) < 0) || ((locate + value - 1) > USED)) + return 1; + + USED = USED - value; + + for (int i = locate; i <= USED; i++) + v[i] = v[i + value]; + + if (((double)USED / (double)LEN) <= 0.3) + shrink(); + + return 0; +} + +int Vec::find(int value) +{ + int i = 0; + for (i; i <= USED; i++) + { + if (v[i] == value) + { + return i; + } + } + + return -1; + +} + +int Vec::getlen() +{ + return LEN; +} + +int Vec::getused() +{ + return USED; +} + +void Vec::printall() +{ + for (int i = 0; i < USED; i++) + printf("%d\n", v[i]); +} \ No newline at end of file