Добавить task3-2.0.cpp
This commit is contained in:
85
task3-2.0.cpp
Normal file
85
task3-2.0.cpp
Normal file
@@ -0,0 +1,85 @@
|
|||||||
|
#include <iostream>
|
||||||
|
using namespace std;
|
||||||
|
|
||||||
|
int* first3Pos(int* a, int n, int& res_n) {
|
||||||
|
int* tmp = new int[3];
|
||||||
|
res_n = 0;
|
||||||
|
for (int i = 0; i < 3 && i < n; ++i)
|
||||||
|
if (a[i] > 0)
|
||||||
|
tmp[res_n++] = a[i];
|
||||||
|
int* res = new int[res_n];
|
||||||
|
for (int i = 0; i < res_n; ++i) res[i] = tmp[i];
|
||||||
|
delete[] tmp;
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
int* last3(int* a, int n, int& res_n) {
|
||||||
|
res_n = (n >= 3) ? 3 : n;
|
||||||
|
int* res = new int[res_n];
|
||||||
|
for (int i = 0; i < res_n; ++i)
|
||||||
|
res[i] = a[n - res_n + i];
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
int* min3(int* a, int n, int& res_n) {
|
||||||
|
int* tmp = new int[n];
|
||||||
|
for (int i = 0; i < n; ++i) tmp[i] = a[i];
|
||||||
|
for (int i = 0; i < n - 1; ++i)
|
||||||
|
for (int j = i + 1; j < n; ++j)
|
||||||
|
if (tmp[i] > tmp[j]) { int t = tmp[i]; tmp[i] = tmp[j]; tmp[j] = t; }
|
||||||
|
res_n = (n >= 3) ? 3 : n;
|
||||||
|
int* res = new int[res_n];
|
||||||
|
for (int i = 0; i < res_n; ++i) res[i] = tmp[i];
|
||||||
|
delete[] tmp;
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
|
typedef int* (*searchFunc)(int*, int, int&);
|
||||||
|
|
||||||
|
void service(int* a, int n, searchFunc f) {
|
||||||
|
int res_n;
|
||||||
|
int* res = f(a, n, res_n);
|
||||||
|
cout << "Result: ";
|
||||||
|
for (int i = 0; i < res_n; ++i) cout << res[i] << " ";
|
||||||
|
cout << endl;
|
||||||
|
delete[] res;
|
||||||
|
}
|
||||||
|
|
||||||
|
int main() {
|
||||||
|
srand(time(NULL));
|
||||||
|
int n;
|
||||||
|
cout << "n(n>=3)= ";
|
||||||
|
cin >> n;
|
||||||
|
if (n < 3) {
|
||||||
|
cerr << "Error: size Array!!";
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
int* arr = new int[n];
|
||||||
|
for (int i = 0; i < n; ++i)
|
||||||
|
arr[i] = rand() % 41 - 20;
|
||||||
|
|
||||||
|
cout << "Array: ";
|
||||||
|
for (int i = 0; i < n; ++i) cout << arr[i] << " ";
|
||||||
|
cout << endl;
|
||||||
|
|
||||||
|
searchFunc arrFunc[3] = { first3Pos, last3, min3 };
|
||||||
|
|
||||||
|
int choice;
|
||||||
|
do {
|
||||||
|
cout << "\nMenu:\n"
|
||||||
|
<< "1) Array of the first 3 elements > 0\n"
|
||||||
|
<< "2) Array of the last 3 elements\n"
|
||||||
|
<< "3) Array of the 3 smallest elements\n"
|
||||||
|
<< "4) Exit\n"
|
||||||
|
<< "Select action (1-4): ";
|
||||||
|
cin >> choice;
|
||||||
|
|
||||||
|
if (choice >= 1 && choice <= 3)
|
||||||
|
service(arr, n, arrFunc[choice - 1]);
|
||||||
|
else if (choice != 4)
|
||||||
|
cout << "Incorrect choice!\n";
|
||||||
|
} while (choice != 4);
|
||||||
|
|
||||||
|
delete[] arr;
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user