1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
|
#include <iostream>
#include <string>
using namespace std;
struct Friend{
string name;
int days;
};
Friend *growArray(Friend *p_friend, int* size){ //Double the size of the array if it needs it
Friend *new_array = new Friend[*size*2];
for(int i =0; i<*size;i++){
new_array[i]=p_friend[i];
}
*size *= 2;
delete [] p_friend;
return new_array;
}
void addFriend(Friend *p_friend, int friends){ // Add a new friend and add parameters
cin.get();
cout << "\nFriend's Name: ";
getline(cin, p_friend[friends].name,'\n');
cout << "How many days since you've talked to "<< p_friend[friends].name << "? ";
cin >> p_friend[friends].days;
}
int findNextSmallest(Friend *p_friend, int size, int currentIndex){ // find the smallest index remaining
int smallestIndex = currentIndex;
//Test each index against the smallest one, if it is, replace
for(int i = currentIndex; i<size; i++){
if(p_friend[i].days<p_friend[smallestIndex].days){
smallestIndex = i;
}
}
return smallestIndex;
}
void swapIndex(Friend *p_friend, int index1, int index2){ //swap the current index with the smallest
Friend temp;
temp.name = p_friend[index1].name;
temp.days = p_friend[index1].days;
p_friend[index1].name = p_friend[index2].name;
p_friend[index1].days = p_friend[index2].days;
p_friend[index2].name = temp.name;
p_friend[index2].days = temp.days;
}
void sortFriends(Friend *p_friend, int size){
//go through array
for(int i = 0;i<size;i++){
//For each index, find the smallest index past that, and swap it
int smallestIndex = findNextSmallest(p_friend, size, i);
swapIndex(p_friend, i, smallestIndex);
}
}
int main(){
//set initial dynamic array size
int size = 2;
//set initial dynamic array index
int friends=0;
//create dynamic array
Friend *p_friend = new Friend[size];
//for while loop
int running = 1;
//Menu selection
int sel = 0;
//main loop
while(running){
for(int i = 0; i <friends; i++){
//print all listed friends
cout << i+1 << ". " << p_friend[i].name << endl << p_friend[i].days << " days.\n\n";
}
//print menu and take selection
cout << "1. Add Friend\n2.Sort Friends\n3.Quit\n";
cin >> sel;
//process selection
if(sel==1){
//dynamically enlarge array if it needs space
if(friends==size-1){
p_friend = growArray(p_friend,&size);
}
//add a friend to the list and update index
addFriend(p_friend, friends);
friends++;
}
if(sel==2){
sortFriends(p_friend,size); // sort friends
}
if(sel==3){
running = 0; // exit program
}
}
}
|