4 Replies - 1897 Views - Last Post: 06 February 2010 - 12:26 AM Rate Topic: -----

#1 niece  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 05-February 10

Sort Struct Array Confussion

Posted 05 February 2010 - 09:30 AM

//This code is for C++, I am trying to figure out how to sort a struct array in alphabetical order using a text in file, also I have to sort my data in 3 parallel arrays by 1) the name of the restaurant (2) phone number (3)favorite dishes. THANK YOU FOR ANY HELP

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

//menu struct 
struct MenuType
{
  //declare the name of the resaurants in the struct
  string name;
  //declare the telephone number of the resaurants in the struct
  string telNum;
  //declare the menu items of the resaurants in the struct
  string menuItems;
}

//main funcion of the code
int main ()
{
   //menu array declaration
   MenuType restaurantArray[3];
   //declare the text in file
   ifstream inFile;
   //open the text in file
   inFile.open("menu.txt");
   //read the resaurant name into the code for text in file
   getline(inFile,MenuType.name);
   //read the resaurant telephone number into the code for text in file
   inFile >> MenuType.telNum;
   //read the resaurant menu items into the code for text in file
   inFile >> MenuType.menuItem;
   //output the restaurant name to screen
   cout << MenuType.name << endl;
   //output the restaurant telephone number to screen
   cout << MenuType.telNum << endl;
   //output the restaurant menu item to screen
   cout << MenuType.menuItem << endl;


   //not sure what to do here as far as sorting in alphabetical order or putting the struct in 3 parallel arrays
   
   
   
   
   system ("PAUSE");
   return 0;
}



This post has been edited by niece: 05 February 2010 - 09:31 AM


Is This A Good Question/Topic? 0
  • +

Replies To: Sort Struct Array Confussion

#2 jjl  Icon User is online

  • Engineer
  • member icon

Reputation: 885
  • View blog
  • Posts: 4,037
  • Joined: 09-June 09

Re: Sort Struct Array Confussion

Posted 05 February 2010 - 09:32 AM

take a look at vectors and the sort function in
#include <algorithm>


Was This Post Helpful? 0
  • +
  • -

#3 Keerigan  Icon User is offline

  • D.I.C Head

Reputation: 10
  • View blog
  • Posts: 55
  • Joined: 04-February 10

Re: Sort Struct Array Confussion

Posted 05 February 2010 - 11:26 AM

It's been awhile since I have done something like this, but what you are going to need to do is overload you less than('<') operator. When you sort structs, sorts don't know what to order them by. So you have to tell it how to know which MenuType is greater than another.

I think the code looks something like this
bool operator &const < ( MenuType const& lhs, MenuType const& rhs )
	{
		return lhs.menuItems < rhs.menuItems
	}


Now this doesn't work, but it's just to give you an idea. I'm just at work right now and if you give me 4 hours, I will return home and find out of my programs that does this. For now, search it up in Google or something.

Sorry I wasn't really of any help,
Keegan Simonse
Was This Post Helpful? 0
  • +
  • -

#4 Munawwar  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 161
  • View blog
  • Posts: 457
  • Joined: 20-January 10

Re: Sort Struct Array Confussion

Posted 05 February 2010 - 12:30 PM

View PostKeerigan, on 05 February 2010 - 10:26 AM, said:

It's been awhile since I have done something like this, but what you are going to need to do is overload you less than('<') operator.

That maybe too difficult a solution for him.(I assume).

@niece
Do you know how to sort an array of integers? You would do the same thing for an array of objects.
If you don't know how to do this then, I say, you better check out some sorting algorithms like ImaSexy said.

For example: use bubble sort.And swap the compared objects like :
if(one.telNum>two.telNum)
{
   MenuType temporary=one; //save the value of one before changing it
   one=two; //Now one=two.Here you lose the original value of one..that's the reason I saved it
   two=temporary;
}


Was This Post Helpful? 0
  • +
  • -

#5 David W  Icon User is offline

  • DIC supporter
  • member icon

Reputation: 262
  • View blog
  • Posts: 1,704
  • Joined: 20-September 08

Re: Sort Struct Array Confussion

Posted 06 February 2010 - 12:26 AM

View Postniece, on 05 February 2010 - 10:30 AM, said:

//This code is for C++, I am trying to figure out how to sort a struct array in alphabetical order using a text in file, also I have to sort my data in 3 parallel arrays by 1) the name of the restaurant (2) phone number (3)favorite dishes. THANK YOU FOR ANY HELP

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

//menu struct 
struct MenuType
{
  //declare the name of the resaurants in the struct
  string name;
  //declare the telephone number of the resaurants in the struct
  string telNum;
  //declare the menu items of the resaurants in the struct
  string menuItems;
}

//main funcion of the code
int main ()
{
   //menu array declaration
   MenuType restaurantArray[3];
   //declare the text in file
   ifstream inFile;
   //open the text in file
   inFile.open("menu.txt");
   //read the resaurant name into the code for text in file
   getline(inFile,MenuType.name);
   //read the resaurant telephone number into the code for text in file
   inFile >> MenuType.telNum;
   //read the resaurant menu items into the code for text in file
   inFile >> MenuType.menuItem;
   //output the restaurant name to screen
   cout << MenuType.name << endl;
   //output the restaurant telephone number to screen
   cout << MenuType.telNum << endl;
   //output the restaurant menu item to screen
   cout << MenuType.menuItem << endl;


   //not sure what to do here as far as sorting in alphabetical order or putting the struct in 3 parallel arrays
   
   
   
   
   system ("PAUSE");
   return 0;
}




The first thing to do is to learn how to read your data file into an array of struc's ... and then to print out all the data records (each/every struct) ...


After you have that coded and working ... then and only then ... think about a sort of the array ... using one field of the struct as the basis for that sort ... and then, print out that sorted array of records

Check here for example of how to read data into an array of struct:

Reading and writing a struct to file in C++ ...


This example of writing ... then reading back an array of struct ... is taken from my on-line Beginning Computer Programming with C++ ...

// structReadWrite.cpp

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

const int MAX_COUNT = 3; // to keep our debuging short and simple

struct MyContacts // a C/C++ style data record ...
{
    string theName;
    string thePhone;
}; // Note: semi-colon here tells compiler we have reached the end of struct

string takeIn( const string& message )
{
    string reply, tmpStr;
    for( ;; ) // a C/C++ forever loop until break (or return, if in a function)
    {
        cout << message << ":  " << flush;
        getline( cin, tmpStr );
        cout << "You input " << tmpStr << " ok (y/n) ? " << flush;
        getline( cin, reply );
        if( reply[0] == 'y' || reply[0] == 'Y' )
            return tmpStr;
    }
}

// the number of contacts taken into the book is returned ...
// (and the updated array of MyContacts is returned ...
//  recall C/C++ arrays 'passed by ref. automatically')
int getBook( MyContacts book[], const int max_num )
{
    bool more = true;
    int i = 0;
    string reply;
    while( i < max_num && more )
    {
        book[i].theName  = takeIn( "Enter name    " );
        book[i].thePhone = takeIn( "Enter phone   " );
        ++i;
        if( i < max_num )
        {
            cout << "More y/n ? " << flush; // defaults to yes (i.e. 'true') ...
            getline( cin, reply );
            more = !( reply[0] == 'n' || reply[0] == 'N' );
        }
    }// end while ...
    return i; // i.e. the count of new contacts
}

// Note: we can pass in a const array ... since
//       we are just printing out values there
void printBook( const MyContacts book[], const int max_num )
{
    cout << "\nYour 'book'   :";
    for( int i = 0; i < max_num; ++i )
    {
        cout << "\n\t\t" << book[i].theName
             << "\n\t\t" << book[i].thePhone
             << endl;
    }
}


void fileBook( ofstream& out, const MyContacts book[], const int max_num )
{
    for( int i = 0; i < max_num; ++i )
    {
        out << book[i].theName << endl
            << book[i].thePhone << endl;
    }
}



int main()
{
    // at compile time, the compiler knows 'MAX_COUNT',
    // so can reserve the requested memory ... for ...
    MyContacts myBook[ MAX_COUNT ]; // an array with MAX_COUNT of MyContacts

    // getBook returns the number of contacts ...
    int numContacts = getBook( myBook, MAX_COUNT );

    printBook( myBook, numContacts );

    ofstream fout( "myFile.txt" );
    fileBook( fout, myBook, numContacts );
    fout.close();

    // just to leave extra room for reading anything extra that might be there
    // (so we can show here that nothing else was there ...)
    MyContacts myBook2[ MAX_COUNT*2 ];
    ifstream fin( "myFile.txt" ); // open an ifstream stream to the file
    int i = 0;
    // fill the array from the file ...
    while
    (
        i < MAX_COUNT*2 &&
        getline(fin, myBook2[i].theName) &&
        getline(fin, myBook2[i].thePhone)
    )
        ++i;
    fin.close(); // close the input file ... i now holds the count of records read

    cout << "From file ... ";
    printBook( myBook2, i );

    cout << "Press 'Enter' to continue ... " << flush;
    cin.get();
}


This post has been edited by David W: 06 February 2010 - 01:08 AM

Was This Post Helpful? 1
  • +
  • -

Page 1 of 1