陣列與向量的比較 向量/陣列相同元素去重
阿新 • • 發佈:2020-12-25
陣列的氣泡排序與向量vector的氣泡排序
#include <bits/stdc++.h>
using namespace std;
template<typename T>
vector<T> bubbleSort_vec(vector<T> a){
vector<T> res = a;
for (int i = 0; i < res.size() - 1; i++){
for (int j = i + 1; j < res.size(); j++){
T temp;
if (res[i] > res[j]){
temp = res[i];
res[i] = res[j];
res[j] = temp;
}
}
}
return res;
}
template<typename T>
T* bubbleSort_arr(T *a, int n){
T* res = new double[n];
for (int i = 0; i < n; i++ ){
res[i] = a[i];
}
T temp;
for (int i = 0; i < n - 1; i++){
for (int j = i + 1; j < n; j++){
if (res[i] > res[j]){
temp = res[i];
res[i] = res[j];
res[j] = temp;
}
}
}
return res;
}
int main(){
vector<double> In1;
cout << "Enter the number of test data:" << endl;
int n;
cin >> n;
double *In2 = new double[n];
cout << "Enter the data:" << endl;
int temp;
for (int i = 0; i < n; i++){
cin >> temp;
In2[i] = temp;
In1.push_back(temp);
}
cout << "Executing bubble sort(vector version)..." << endl;
vector<double> res1;
res1 = bubbleSort_vec(In1);
cout << "result:" << endl;
for (int i = 0; i < res1.size(); i++){
cout << res1[i] << endl;
}
cout << "\n\n\n";
cout << "Executing bubble sort(array version)..." << endl;
double *res2 = bubbleSort_arr(In2,n);
cout << "result:" << endl;
for (int i = 0; i < n; i++){
cout << *(res2 + i) << endl;
}
delete[] In2;
delete res2;
cout << "process finished..." << endl;
system("pause");
return 0;
}
利用std的set實現向量相同元素去重以及陣列簡單去重
#include <bits/stdc++.h>
using namespace std;
template<typename T>
vector<T> delRepeat_v1(vector<T> a){
set<T> temp;
vector<T> res;
for (int i = 0; i < a.size(); i++){
if (!temp.count(a[i])){
temp.insert(a[i]);
res.push_back(a[i]);
}
}
return res;
}
template<typename T>
vector<T> delRepeat_v2(vector<T> a){
vector<T> temp;
for (int i = 0; i < a.size(); i++){
int flag = 1;
for (int j = 0; j < temp.size(); j++){
if (a[i] == a[j]) {
flag = 0;
break;
}
}
if (flag) temp.push_back(a[i]);
}
return temp;
}
int main(){
cout << "enter the number of test data:\n";
int n;
cin >> n;
vector<double> In;
double temp;
cout << "enter the data:" << endl;
for (int i = 0; i < n; i++){
cin >> temp;
In.push_back(temp);
}
cout << "delete the repeated data(use set to ensure every element is unique)...\n";
vector<double> res = delRepeat_v1(In);
cout << "result:" << endl;
for (int i = 0; i < res.size(); i++){
cout << res[i] << endl;
}
cout << "\n\n\n";
cout << "delete the repeated data(ordinary version)...\n";
vector<double> res2 = delRepeat_v2(In);
cout << "result:" << endl;
for (int i = 0; i < res.size(); i++){
cout << res[i] << endl;
}
cout << "process finished...\n";
return 0;
}