Преглед на файлове

第二章二小节第6题

DESKTOP-C21C1Q8\tangs преди 6 години
родител
ревизия
fc1ab300e1
променени са 1 файла, в които са добавени 95 реда и са изтрити 0 реда
  1. 95 0
      1/1/6/main.cpp

+ 95 - 0
1/1/6/main.cpp

@@ -0,0 +1,95 @@
+//
+// Created by tangs on 2018/9/19.
+//
+
+#include <iostream>
+#include <time.h>
+#include <algorithm>
+
+using namespace std;
+
+struct Digit {
+    int *Ary;
+    int Length;
+
+    Digit(int length) {
+        int *tempAry = new int[length];
+        this->Length = 2*length;
+        this->Ary = new int[this->Length];
+
+
+        for (int i = 0; i < length;i ++){
+            tempAry[i] = rand();
+        }
+
+        for (int i =0 ;i < length;i ++){
+            this->Ary[i] = tempAry[i];
+            this->Ary[length + i] = tempAry[i];
+        }
+
+        this->Sort();
+    }
+
+    ~Digit() {
+        delete(this->Ary);
+        this->Length = 0;
+    }
+
+
+    void Sort();
+    void Print();
+    void DelRepeat();
+};
+
+void Digit::Print() {
+    cout << "Num " << this->Length << endl;
+    for (int i = 0; i < this->Length; i++) {
+        cout << this->Ary[i];
+        if (i == this->Length - 1) {
+            cout << endl;
+        } else {
+            cout << " ";
+        }
+    }
+}
+
+/**
+ * 将顺序表排序生成有序顺序表
+ */
+void Digit::Sort() {
+    sort(this->Ary,this->Ary + this->Length);
+}
+
+/**
+ * 删除有序顺序表中重复的元素
+ * @return
+ */
+void Digit::DelRepeat() {
+    if (this->Length < 1) {
+        return;
+    }
+    int temp = this->Ary[0];
+    int k = 1;
+    for (int i = 1; i < this->Length; i++) {
+        if (this->Ary[i] != temp) {
+            temp = this->Ary[i];
+            this->Ary[k] = this->Ary[i];
+            k++;
+        }
+    }
+    this->Length = k;
+}
+
+
+/**
+ * 从有序表中删除所有其值重复的元素,使表中所有元素的值均不同
+ * @return
+ */
+int main(){
+    srand((unsigned)time(NULL));
+
+    Digit digit(10);
+    digit.Print();
+    digit.DelRepeat();
+    digit.Print();
+}