Sorting problems in own vector

Dear C++ heroes,

Today I seek your help with my program for university, first of all here is the assignment:

----------------------------------------------------------------
The university decided to make a new program to keep track of which employees are in which room. This digital address book can be managed from the command line.

A room number always consists of a letter followed by 3 digits. If multiple employees are in the same room, the output of list should be sorted by room number first, and then sorted by name (alphabetically). Implement this program. The following restrictions apply:

You are not allowed to use any class that you have not programmed yourself (including std::vector), except for std::string, std::cin, std::cout, and std::cerr.
You are not allowed to create an array or a pointer to a part of memory that is larger than the amount of entries you need to store.
A correct execution of this program is shown below:
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
> remove Thilo
error: entry does not exist
> add Thilo P322
> add Matty F153
> list
Matty is in room F153
Thilo is in room P322
> move Matty T427
> list
Thilo is in room P322
Matty is in room T427
> find Thilo
Thilo is in room P322
> move Thilo T427
> list
Matty is in room T427
Thilo is in room T427
> clear
> list
> add Jorg T437
> add Femke T447
> remove Jorg
> list
Femke is in room T447
> exit

------------------------------------------------------------

So I managed to do everything but I still struggle against two parts:
- sorting in my list function
- error handling, checking whether or not a name is not in the list when trying to remove.

so here is my code:
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
#include <iostream>

struct Combo{
    std::string teacher;
    std::string roomNumber;
};

class Data{
    private:
        int size;
        Combo *elements;
    public:
        Data(): size{0}, elements{new Combo [0]}{
        }
        
        ~Data(){
            delete []elements;
        }
        
        Combo at(int index){
            return elements[index];
        }
        
        void push_back(Combo value){
            Combo *save = new Combo[size + 1];
            if(size == 0){
                save[0] = value;
            }   
            if(size > 0 ){
                for(int i = 0 ; i < size ; i++){
                    save[i] = elements[i];
                    if(i == (size - 1)){
                        save[i + 1] = value;
                    }
                }
            }
            delete[] elements;
            elements = save;
            size ++;
        }
        
        void list(){             // So I struggle with this function.
            bool sort = false;   // I try to use bubble-sort, but failed.
            
            while(sort == false){
            Combo *save = new Combo[size];
                for(int i = 0; i < size - 1; i++){
                    bool sortCheck = false;
                    if(elements[i].roomNumber > elements[i + 1].roomNumber){
                        save[i] = elements[i + 1];
                        elements[i] = save[i + 1];
                        sortCheck = true;
                    }
                    else if(elements[i].roomNumber < elements[i + 1].roomNumber){
                        save[i] = elements[i];
                        save[i + 1] = elements[i + 1];
                        sortCheck = true;
                    }
                    else if(sortCheck == false){
                        sort = true;
                    }
                }
            }
        }
        
        std::string return_teacher(int index){
            return elements[index].teacher;
        }
        std::string return_roomNumber(int index){
            return elements[index].roomNumber;
        }
        
        void delete_teacher(std::string teacher){  // and with this one.
            Combo *save = new Combo[(size - 1)];
            bool nextElement = false;
            int teacherCheck = 0;
            for(int i = 0 ; i < (size - 1) ; i++){
                teacherCheck ++;
                if (teacher == elements[i].teacher || nextElement == true){
                    nextElement = true;
                    save[i] = elements[i+1];
                }
                else if(teacher != elements[i].teacher && nextElement == false){
                    save[i] = elements[i];
                }
                else if(teacherCheck == (size - 1)){ 
                    throw std::runtime_error ("entry does not exist");
                } // If every element has been checked, throw error (what I try).
            }
            delete[] elements;
            elements = save;
            size --;
        }
        
        void move(std::string teacher, std::string roomNumber){
            Combo *save = new Combo[size];
            for(int i = 0 ; i < size ; i++){
                save[i] = elements[i];
                if(teacher == elements[i].teacher){
                    save[i].roomNumber = roomNumber;
                }
            }
            delete[] elements;
            elements = save;
        }
        
        void delete_elements(){
            Combo *save = new Combo[0];
            delete[] elements;
            elements = save;
            size = 0;
        }
        
        int length(){
            return size;
        }
};

int main (){
    Combo objectCombo;
    Data vector;
    std::string choice, teacher, roomNumber;
    
    while(std::cin){
        try{
            std::cout << "> ";
            std::cin >> choice;
            
            if(choice == "add"){
                std::cin >> teacher;
                std::cin >> roomNumber;
                if(!isalpha(roomNumber[0]) || !isdigit(roomNumber[1,2,3]) || roomNumber.length() != 4){
                    throw std::runtime_error("Invalid roomnumber");
                }
                
                objectCombo.teacher = teacher;
                objectCombo.roomNumber = roomNumber;
                vector.push_back(objectCombo);
            }
            
            else if(choice == "remove"){
                std::cin >> teacher;
                
                vector.delete_teacher(teacher);
            }  
            
            else if(choice == "find"){
                std::cin >> teacher;
            
                for(int i = 0 ; i < vector.length() ; i++){
                    if(teacher == vector.return_teacher(i)){
                        std::cout << vector.return_teacher(i) << " is in room " << vector.return_roomNumber(i) << std::endl;
                    }
                }
            }     
            
            else if(choice == "move"){
                std::cin >> teacher;
                std::cin >> roomNumber;
                
                vector.move(teacher, roomNumber);
            }
            
            else if(choice == "list"){
                for(int i = 0 ; i < vector.length() ; i++){
                    vector.list();
                    std::cout << vector.return_teacher(i) << " is in room " << vector.return_roomNumber(i) << std::endl;
                }
            }
            
            else if(choice == "exit"){
                return 1;
            }
            
            else if(choice == "clear"){
                vector.delete_elements();
            }
            
        }
        catch(std::runtime_error e){
            std::cerr << "Error: " << e.what() << std::endl;
        }
    }
    return 0;
}




1 month ago I started programming, I already struggled with writing a hello-world program in this programming language haha. the deadline for my assignment is 23/10/2017 23:59. It kind of decides whether or not I pass this course, so a lot of pressure is on me.

I hope anyone can see what I did wrong in this case and might help a brother out! I hope to do the same thing for this community once I get more advanced.

Cheers!

Last edited on
I have written in comments for what part of the code I struggle with, if there any other tips regarding my code please let me know.

Sincerely
Sounds like a sticky situation. First I'll mention some things that should help you with your current implementation.

First, I don't believe you want to be using std::runtime error as these typically terminate your program running. I would check for the error condition and then print the output to the screen using cout.
1
2
3
4
5
//instead of 
throw std::runtime_error ("entry does not exist");

//use this
std::cout << "error: entry does not exist\n"


Next lets look at your list function in data. First, you are missing the sort by name if the roomnumber is the same. Secondly,for sorting a list with bubble sort in your case you do not need to create a new array to sort your list. You can use a temporary object. Also, the typical bubble sort looks for true Boolean if elements have been swapped. Instead of giving you new code, I will put in your current function and add comments explaining what should be changed.

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
void list()
{
     bool sort = false;   //start with this as true
            
            while(sort == false)//change condition to while(sort)
            {
            Combo *save = new Combo[size];//get rid of this you wont need it
            //first thing in the loop should set sort to false;
                for(int i = 0; i < size - 1; i++){
                    bool sortCheck = false;//remove this
                    if(elements[i].roomNumber > elements[i + 1].roomNumber){
                       //here create a temporary object of type Combo
                      //here set elements[i] to elements[I+1]
                      //here set elements[i] to the temporary combo object
                        save[i] = elements[i + 1];//can remove this
                        elements[i] = save[i + 1];//can remove this
                        sortCheck = true;//can remove this
                    }
                    else if(elements[i].roomNumber < elements[i + 1].roomNumber)//change this conditional to check if the rooms are equal
                   {
                        //create new conditional comparing teacher name
                        //here create a temporary object of type Combo
                      //here set elements[i] to elements[I+1]
                      //here set elements[i] to the temporary combo object
                        save[i] = elements[i]; //remove this
                        save[i + 1] = elements[i + 1];//remove this
                        sortCheck = true;//remove this
                    }
                    else if(sortCheck == false)//this condition is not needed anymore
                   {
                        sort = true;
                    }
                }
            }

}


As an aside, I would not use the name list for this function since it is not listing, but is sorting. sort might be more appropriate.

The last thing is your delete function. It will always delete an item weather it is there or not. This is because you create and return a combo array of smaller size regardless of if the name exists or not. You need to determine if the name exists first and if it does delete. otherwise say that it does not exist.

I would suggest writing a function that returns an int which is the index of the teacher if they exist. This could be implemented by the following pseudo code
1
2
3
4
5
6
7
8
9
int findTeacherIndex(string teacher)
{
  //loop through the current teachers for each index
      //compare teacher with teacher of the current index
         //if it matches return the index
  //end loop
  //if no match is found return an integer you can check against. -1 is common
  //because there cannot be a negative index in an array
}


after this function is working, creating the delete should be a little easier. There are a number of ways to implement the following pseudo code is the method I used
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
void delete_teacher(std::string teacher)
{
    int teachIndex = findTeacherIndex(teacher); //use the find teacher index t get a value;

    //check if the index is equal to -1 or whichever value is returned if the teacher is not found
        //print out your error
    else {//the teacher exists
       //create your combo array of size -1
       //create integer index for the new combo array
      //create integer for the current array which we will be deleting a teacher from
     //in a for loop from the current array index from 0 to size minus 1
        //check if our current index = our teacher index
           //if it is, skip this index by incrementing the current array index
        //check to ensure that our current index is still less than size-1
            //if it is then newarray[newIndex] = currentArray[currentIndex]
            //also make sure that you increment the new index otherwise you will continue to overwrite only the first index
     //end your for loop
       delete[] elements;
       elements = save;
       size --;
    }//end else
}


With these changes I have a working version of your code with the specifications at the top of your post. Let me know if you need more clarification.


On another note, if you need to implement something in the future like this, you may want to look into a linked list implementation that you can sort as you add items to it instead of later. It would also eliminate the need to recreate the combo array over and over again.

I apologize in advance if there are formatting or other problems with this response. Please let me know and I will edit it.

Good luck on finishing up your assignment.
Last edited on
Topic archived. No new replies allowed.