Struct - Array Sorting...this is frustrating...

This is a discussion on Struct - Array Sorting...this is frustrating... within the C++ Programming forums, part of the General Programming Boards category; Alright, I know that this might be really easy for some people, but I am having one heck of a ...

  1. #1
    Registered User
    Join Date
    May 2010
    Posts
    19

    Exclamation Struct - Array Sorting...this is frustrating...

    Alright, I know that this might be really easy for some people, but I am having one heck of a time figuring this out! I was wondering if someone could please help me figure this out...I am in need and this code needs to be done by tomorrow evening, so i was wondering if I could get some straight answers here. :P I am using Dev C++, and here is my code.

    Code:
    #include <iostream>
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <algorithm>
    
    using namespace std;
     
    
    #define ePos 3 // Define the amount of employees
    
    // Create the structure for the employees
    struct Employee_t {
           string eFName, eLName, eStreetName, eCity, eState;
           int eStreetNum, eZip, eID;
    }employee [ePos]; // Set a default array to store employees
    
    // Declare the fuctions before main process for use
    void printEmployee (Employee_t Employee);
    void employeeSort(string array[], int len);
    
    // Start main
    int main()
    { 
        // Define the position of the array for employee
        int pos;
        
        // Ask for input of employees using a for statement to fill the array
        for (pos = 0; pos < ePos; pos++)
              {
                   cout << "\nEnter employee's -\n";
                   // Ask and store employee's name
                   cout << "First Name: ";
                   cin >> employee[pos].eFName;
                   // Ask and store employee's last name
                   cout << "Last Name: ";
                   cin >> employee[pos].eLName;
                   // Ask and store employee's street number
                   cout << "Street Number: ";
                   cin >> employee[pos].eStreetNum;
                   // Ask and store employee's street number
                   cout << "Street Name: ";
                   cin >> employee[pos].eStreetName;
                   // Ask and store employee's city
                   cout << "City: ";
                   cin >> employee[pos].eCity;
                   // Ask and store employee's state
                   cout << "State: ";
                   cin >> employee[pos].eState;
                   // Ask and store employee's zip code
                   cout << "Zip Code: ";
                   cin >> employee[pos].eZip;
                   // Ask and store employee's customer ID
                   cout << "Customer ID: ";
                   cin >> employee[pos].eID;
              }
        // Display the entered employees       
        cout << "\nYou have entered these employees: \n";
        // Used to display employee's information
        for (pos = 0; pos < ePos; pos++)
        {
            printEmployee (employee[pos]);
        }
        
        employeeSort(employee[pos], 4);
    
        // Pause before safe shutdown of program
        system("PAUSE");
        return EXIT_SUCCESS;
    }
    
    // Print the employee's information
    void printEmployee (Employee_t Employee)
    {
         cout << "\n" << Employee.eLName << ", " << Employee.eFName << endl;
         cout << Employee.eStreetNum << " " << Employee.eStreetName << endl;
         cout << Employee.eCity << ", " << Employee.eState << " " << Employee.eZip << endl;
         
    }      
    
    // Sorting function for employees
    
    void employeeSort(string array[], int len) {
    	int i, j;
    	string check;
    	
    	for(i=1; i<len; i++) {
    		check = array[i];
    		for(j=i; j>=1 && (check < array[j-1]); j--) {
    			array[j] = array[j-1];
    			array[j-1] = check;
    		}
    	}
    }
    If someone could please lead me in the right direction for sorting my employee struct after the data is entered, then I would be so happy!!! Thank you so much in advance!

  2. #2
    Registered User
    Join Date
    Aug 2005
    Posts
    266
    if you are allowed to use algorithm library

    do something like this

    Code:
    sort(array, array+len, comp());
    where you supply your own comparator method

    like this

    Code:
    struct comp
    {
    //overload () operator here with a compare on the struct
    }
    check this out
    C++ Tutorial - Sorting STL Containers | Switch on the Code

    if you ARE NOT allowed to use sort function, then this isn't much help

  3. #3
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,299
    If you want to sort the array, why would you only be passing a single item to your insertion sort routine?
    Actually pos is 3 at that point, so you're trying to pass an item that is one past the end of the array. You should just pass the array itself.
    Also, why would you pass 4 when you know full well that there are only 3 array elements?

    Other than that, you're supposed to be the one asking the questions first.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  4. #4
    Registered User
    Join Date
    May 2010
    Posts
    19
    Sorry about that whole passing over the 3 and 4...I was trying to see if something would work...it was the fact that I needed to pass the whole array over...I have tried so many different solutions, but I haven't been able to find one that sorted the whole struct with the array inside of it. I will give that sort function a shot real fast, but if someone could give me some help with what I am using, that would be great! Thanks for the fast replies on this though! :P

    EDIT: Alright, the algorithm one didn't work because I was just testing to see if it worked, but it didn't...so...

    I just wanted to show you the error that I get:
    http://tinypic.com/m/a4n0x0/3

    Please, someone help me! This is so frustrating! ><
    Last edited by RadethDart; 05-13-2010 at 07:05 AM.

  5. #5
    Registered User
    Join Date
    Apr 2010
    Posts
    2
    this programmer look like so easy ,but i don't know what is it wrong

  6. #6
    Registered User
    Join Date
    May 2010
    Posts
    2,701
    You have defined [code] void employeeSort(string array[], int len); [\code]
    and are trying to pass the structure to this function [code] employeeSort(employee[pos], 4); [\code]

    Also to be of any further help I need to know how you want the structure sorted.

  7. #7
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,299
    Your sort routine has to take an array of Employee_t, not an array of strings.

  8. #8
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,660
    Quote Originally Posted by rodrigorules View Post
    if you are allowed to use algorithm library

    do something like this

    <snip>

    where you supply your own comparator method
    For that matter, you can also just overload less-than, the default comparator choice of the standard sorts.

  9. #9
    Registered User
    Join Date
    May 2010
    Posts
    19
    Quote Originally Posted by iMalc View Post
    Your sort routine has to take an array of Employee_t, not an array of strings.
    Alright, iMalc, if you can tell me all of these things, could you at least take the time to walk me through it a little rather than just saying a few things and leaving? I really am in need of help here...

    Oh, and I need the structure to be sorted by the eLName string. But I don't know how to keep all of the data with it and push everything through...that is why I am having trouble with sorting this structure; I have never sorted structures inside of arrays.

  10. #10
    Registered User
    Join Date
    May 2010
    Posts
    19
    I was going about this in the wrong fashion. Thanks for the help anyways!! Here is the final code on what I was trying at! :P

    Code:
    /******************************************************
    
    ** Name: Joshua Long
    
    ** Filename: CPP_FINAL1.cpp
    
    ** Project Description: Enter the number of employees you want
       to input into the database, enter all of the employees and
       then sort the employees by last name. Prompt user to search
       for an employee by last name then display employee.
    
    ** Output: Employee data that was entered and then organized
       by the program to have better formatting.
    
    ** Input: Employee data
    
    ** Strees Level: Very HIGH ;)
    
    ******************************************************/
    
    // Include Files
    #include <iostream> // used for cin, cout
    #include <iomanip>
    #include <string.h>
    #include <stdio.h> 
    using namespace std;
    
    const int MAX_NAME_SIZE = 22; // Max size for names
    const int MAX_SIZE = 25; // Max size for all other strings
    
    // Employee Structure (Used for all employees
    struct Employee {
           // Chars used instead of strings for use of spaces
           char eName[MAX_NAME_SIZE], eLName[MAX_NAME_SIZE], eStreetName[MAX_SIZE], eCity[MAX_SIZE], eState[MAX_SIZE]; 
           int eID, eStreetNum, eZip;
           void inNameeID();
    };
    
    
    // Max amount of employees allowed in program
    const int MAX_EmployeeS = 50;
    
    // The Employees class
    class Employees {
          public:
                 // Fuction Prototypes
                 void inEmployees();
                 void inNameeID();
                 void sortNameeID();
                 void print(const char *prompt);
                 
                 // Private variables
                 private:
                         Employee data[MAX_EmployeeS];
                         int size;
    };
    
    
    // Main Processing
    int main() {
        //xEmployee.print("Original list"); // Used to print original
        //xEmployee.print("Alphabetized list"); // Used to print aplha list
        
        // Create new instance of Employees (stores all employee's data)
        Employees xEmployee;
        
        // Display which employee is being input
        xEmployee.inEmployees();
        // Prompt for input of the employee data
        xEmployee.inNameeID();
        // Sort the employee data by last name
        xEmployee.sortNameeID();
        
        // Print the employees that have been entered
        xEmployee.print("Sorted Employee List");
        
        //Pause program before shutting down
        system("PAUSE");
            
    }
    
    
    // Prompt for the user input on the employee's data
    void Employee::inNameeID() {
            cout << "First Name: ";
            cin.getline( eName, MAX_NAME_SIZE); // First Name
            cout << "Last Name: ";
            cin.getline( eLName, MAX_NAME_SIZE); // Last Name
            cout << "Street Number: ";
            cin >> eStreetNum; cin.ignore(); // Street Number
            cout << "Street Name: ";
            cin.getline( eStreetName, MAX_SIZE); // Street Name
            cout << "City: ";
            cin.getline( eCity, MAX_SIZE); // City
            cout << "State: ";
            cin.getline( eState, MAX_SIZE); // State
            cout << "Zip Code: ";
            cin >> eZip; cin.ignore(); // Zip Code
            cout << "Customer ID: ";
            cin >> eID; cin.ignore();  // Customer ID
            cout << endl;
    }
    
    
    // Prompt for how many employees should be entered
    void Employees::inEmployees() {
            cout << "Enter number of Employees (1 . . " << MAX_EmployeeS << ")" << endl << '>';
            cin >> size; cin.ignore(); 
    }
    
    
    // Display which employee is being entered
    void Employees::inNameeID() {
            for ( int count = 0; count < size; count++ ) {
                    cout << "Employee " << (count + 1) << endl;
                    data[count].inNameeID();
            }
    }
    
    
    // Print the employees that have been entered
    void Employees::print(const char *prompt) {
            cout << prompt << endl;
            cout << "------------------------------" << endl;
            for ( int count = 0; count <size; count++ ) {
                    cout << data[count].eLName << ", " << data[count].eName  << "\n"; // Last Name, First Name
                    cout << data[count].eStreetNum << " " << data[count].eStreetName << "\n"; // Street Number Street Name
                    cout << data[count].eCity << ", " << data[count].eState << " " << data[count].eZip << "\n"; // City, State Zip
                    //cout << setw( 8 ) << left << "Customer ID: " <<data[count].eID << "\n"; // Customer ID
                    cout << endl;
            }
            cout << endl;
    }
    
    
    // Sort fuction used to sort through the employee struct and sort by last name else, customer ID
    void Employees::sortNameeID() {
             int smallestOrLargest;
             int index;
             
             for ( int i = 0; i < size-1; i++ ) {
                    int smallestOrLargest = i;
                     
                    for ( int index = i + 1; index < size; index++ ) {
                            int cmpName = strcmp(data[index].eLName, data[smallestOrLargest].eLName);
                            if (cmpName<0) { smallestOrLargest = index;
                            } else if (cmpName==0) { // names match
                                    if (data[index].eID<data[smallestOrLargest].eID) {
                                            smallestOrLargest = index;
                                    }
                            }
                    }
                    
                    if (smallestOrLargest != i) { //swap them
                            Employee temp = data[i];
                            data[i] = data[smallestOrLargest];
                            data[smallestOrLargest] = temp;
                    }
            }
    }
    Obviously it isn't completed from the description, but I thought you guess/gals(if any) might want to see how it turned out!!

  11. #11
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,299
    Yeah sorry, the time I have free for posting here is becoming more and more limited over time. I sometimes do go into plenty of detail explaining stuff, but then I don't get time to help many others, so I end up limiting myself to just a few hints here and there some days. Luckily it's Friday evening now - bring on the weekend!

    I see you switched from Insertion Sort to Selection Sort. That's an interesing change, although it has no overall bearing on the result. You are though at least obviously able to implement multiple sorting algorithms correctly, which is pretty good in my book.
    You declared index twice inside your sorting routine, and could have deleted the first one, but nevermind. This code is certainly improved now. I assume it compiles and runs okay? If so, you're probably ahead of several others at least. A program that doesn't quite do everything necessary but does at least does each thing correctly, is not too shabby at all.
    Heck you've even got some const-correctness in there for good measure. That quite possibly puts you ahead of the average for your class.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  12. #12
    Registered User
    Join Date
    May 2010
    Posts
    19
    Haha, thanks there iMalc! Sorry for flipping out a little, I was just upset that I couldn't get help, even though I just problem solved and made it through it. :P

    I thank you a ton, and I am also working on that sorting help that you gave me, I will tell you how it turns out! Thanks a ton!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. need help about array of struct
    By rob90 in forum C Programming
    Replies: 10
    Last Post: 12-27-2009, 12:55 PM
  2. 2 problems: Struct array and pointer + struct
    By v1n1c1u5 in forum C Programming
    Replies: 0
    Last Post: 12-13-2009, 04:38 PM
  3. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM
  4. towers of hanoi problem
    By aik_21 in forum C Programming
    Replies: 1
    Last Post: 10-02-2004, 01:34 PM
  5. Request for comments
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 01-02-2004, 09:33 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21