Created
October 10, 2019 19:22
-
-
Save MichaelStett/f0d99f3ebbd3adec3b194c0b6966ae86 to your computer and use it in GitHub Desktop.
MyStruct
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <fstream> | |
#include <string> | |
#include <ctime> | |
#define charB 66 | |
#define charS 83 | |
using std::fstream; | |
using std::string; | |
using std::getline; | |
using std::swap; | |
using std::stoi; | |
struct MyStruct { | |
int MyInt; | |
char MyChar; | |
float MyFloat; | |
static MyStruct** Rand(MyStruct** tab, int N) { | |
srand(time(nullptr)); | |
int temp = 0; | |
for (int i = 0; i < N - 1; i++) { | |
do { | |
temp = (rand() % 9000) - 1000; | |
} while (Exist(tab, N, temp)); | |
tab[i]->MyInt = temp; | |
tab[i]->MyChar = rand() % (charS - charB) + charB; | |
tab[i]->MyFloat = 1000.0f + (float)i + 1; | |
} | |
return tab; | |
} | |
static void Sort(MyStruct** tab, int N) { | |
bool flag; | |
for (int i = 0; i < N - 1; i++) { | |
flag = false; | |
for (int j = 0; j < N - i - 1; j++) | |
if (tab[j]->MyInt > tab[j + 1]->MyInt) { | |
Swap(tab[j], tab[j + 1]); | |
flag = true; | |
} | |
if (!flag) | |
return; | |
} | |
} | |
static int FindChar(MyStruct** tab, int N, char X) { | |
int num = 0; | |
for (int i = 0; i < N - 1; i++) | |
if (tab[i]->MyChar == X) | |
num++; | |
return num; | |
} | |
static void Print20(MyStruct** tab) { | |
for (int i = 0; i < 20; i++) | |
printf("%i %c %.0f \n", tab[i]->MyInt, tab[i]->MyChar, tab[i]->MyFloat); | |
} | |
static void Delete(MyStruct** tab, int N) { | |
for (int i = 0; i < N; i++) | |
delete tab[i]; | |
delete tab; | |
} | |
private: | |
static void Swap(MyStruct* tab, MyStruct* tab2) { | |
swap(tab->MyInt, tab2->MyInt); | |
swap(tab->MyChar, tab2->MyChar); | |
swap(tab->MyFloat, tab2->MyFloat); | |
} | |
static bool Exist(MyStruct** tab, int N, int check) { | |
for (int i = 0; i < N; i++) | |
if (tab[i]->MyInt == check) | |
return true; | |
return false; | |
} | |
}; | |
int main() { | |
clock_t begin, end; | |
begin = clock(); | |
int N; | |
char X; | |
string line; | |
fstream file{ "inlab01.txt" }; | |
if (file.is_open()) | |
{ | |
getline(file, line); | |
N = stoi(line); | |
X = line[N < 10 ? 2 : N < 100 ? 3 : N < 1000 ? 4 : N < 10000 ? 5 : 6]; | |
auto** tab = new MyStruct * [N]; | |
for (int i = 0; i < N; i++) | |
tab[i] = new MyStruct(); | |
MyStruct::Rand(tab, N); | |
MyStruct::Sort(tab, N); | |
MyStruct::Print20(tab); | |
printf(" %c -> %i \n", X, MyStruct::FindChar(tab, N, X)); | |
MyStruct::Delete(tab, N); | |
file.close(); | |
} | |
else | |
printf("No file. \n"); | |
end = clock(); | |
printf("Time: %0.5fs", (double)(end - begin) / CLOCKS_PER_SEC); | |
getchar(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment