Sorting Multiple Vectors

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • xtheendx
    New Member
    • Apr 2008
    • 11

    Sorting Multiple Vectors

    In my program i have three sperate vectors that store the students last name, first and score. I need to sort it by last name and print the contents of the vectors lastname, firstname: score. Well i have got it doing that for the most part. But after it sorts the lastnames the first names and scores are still in the same postion in their vectors, so when it prints the reults the last names are with the wrong first name and score. any ideas?

    Code:
     #include <iostream>  // allows the program to output data to the screen
    #include <conio.h>
    #include  <iomanip>
    #include <cstdlib>
    #include <string>
    #include <vector>
    #include <algorithm>
    #include <numeric>
    #include <fstream>
    #include <ios>
    #include <istream>
    #include <limits>
    #include "students.h" // gradebook class defintion
    
    
    using std::cout; // program uses cout
    using std::cin; // program uses cin
    using std::endl; // program uses endl
    using std::setprecision; // set numeric output precision
    using std::fixed; // ensures that decimal point is displayed
    using std::setw;
    using std::string;
    using std::vector;
    using std::max;
    
    
    void  students::displayMessage()
    {
            
        cout << endl << "Welcome to the Student Scores Application." << endl << endl;
    }
            
    
    void students::getData()
    {
        int numStudents = 0;
        string name;	
        int score = 0;
        int i = 0;
        
        cout <<"Enter number of students to enter: ";
        cin >> numStudents;
        cin.ignore ( std::numeric_limits<std::streamsize>::max(), '\n' );
        
        vector<string> student_lastnames;
        vector<string> student_firstnames;
        vector <int> student_score;
    
        do
       
        { 
                cout << endl << "Student " << i + 1 <<" last name: "; 
                cin >> name;
          	    cin.ignore ( std::numeric_limits<std::streamsize>::max(), '\n' );    
    	    student_lastnames.push_back(name);
        	    
    
    
    
                cout << "Student " << i + 1 <<" first name: "; 
                cin >> name;
         	    cin.ignore ( std::numeric_limits<std::streamsize>::max(), '\n' );
    	    student_firstnames.push_back(name);
          
                cout << "Student " << i + 1 <<" score: "; 
                cin >> score;
    	    cout << endl;
    	    cin.ignore ( std::numeric_limits<std::streamsize>::max(), '\n' );    
    	    student_score.push_back(score);
         		
         i++;
         }
    
         while ( i < numStudents);
        
    
                // sort them alphabetically
            sort (student_lastnames.begin(), student_lastnames.end());
    
        for (int i =0; i < student_lastnames.size(); i++)
        {
                cout << student_lastnames[i] << ", " << student_firstnames[i] << ": " << student_score[i] << endl;
        }
          
        
    
    }
    
    void students::End()
    {
    	cout << endl << endl << "Press any key to continue..."; // prompts the user to continue or quit 
    	char c = getch();
    }
    
    
    // function main begins program exectuion
    int main() 
    {
        students mystudent;
        
        mystudent.displayMessage();
    
        mystudent.getData(); 
        
        mystudent.End();	   
        
    }
  • Laharl
    Recognized Expert Contributor
    • Sep 2007
    • 849

    #2
    Use a std::map<string , std::pair<doubl e, string> > (the first string is for the last name, the pair holds two objects (score+first name)) or make a 'student' struct or class. Either will make your life easier. The map stores its keys in sorted order to begin with, and you can overload operators for the struct/class so that they can be easily sorted.

    Comment

    • xtheendx
      New Member
      • Apr 2008
      • 11

      #3
      Originally posted by Laharl
      Use a std::map<string , std::pair<doubl e, string> > (the first string is for the last name, the pair holds two objects (score+first name)) or make a 'student' struct or class. Either will make your life easier. The map stores its keys in sorted order to begin with, and you can overload operators for the struct/class so that they can be easily sorted.

      how would I use the map and pair in my code. I have never heard fo them. sorry if it is dumb question, but do i leave it how you wrote it or should i plud in my variable names... also is their a special #include i should use? thanks for the help.

      Comment

      • Laharl
        Recognized Expert Contributor
        • Sep 2007
        • 849

        #4
        Go here for a reference on the STL map and pair.

        Comment

        • RRick
          Recognized Expert Contributor
          • Feb 2007
          • 463

          #5
          If you are more comfortable with vectors, you can make a structure that contains all your data and then create vector of that structure. [code=cpp]struct Stuff { string firstName, lastName, etc };
          vector<Stuff> vecStuff;[/code]

          To sort the vector you'll have to use the sort function in algorithm.h. The sort function takes 3 parameters: start iterator, end iterator, and a function that returns a bool for when one Stuff is less than another. I'll let you write the function, but the call looks like:[code=cpp]
          bool stuffA_lt_stuff B( const Stuff & a, const Stuff & b)
          { you get to define this }

          std::sort( vecStuff.begin( ), vectStuff.end() , stuffA_lt_stuff B);
          [/code]The trick here is that sort uses your 'less than' function to sort the objects. If you want to reverse the sort, make a 'greater than or equal to' function.

          Comment

          • primeSo
            New Member
            • Aug 2007
            • 35

            #6
            Just my personal opinion.

            I think you have some miss understanding with what your code is doing compare to what you actually wanted it to do.

            First of all, you have wroteyou have 3 vectors which store first name, last name and score respectively. Then you wanted them to be sorted by last name.
            After your sorting operation, what is sorted is only the vector storing the last name, the other two still remain the same order as previous. Thus, your code certainly not work as you expected.

            My suggestion is, redesign.

            For example:
            Code:
            class Student{
               private:
                  string lastName;
                  string firstName;
                  double score;
            };
            
            int main(){
               vector<Student> studentList;
            
               //treat the 3 variables as a whole.
               Student std1;
            
               std1.lastName = "Prime";
               std1.firstName = "Optimus";
               std1.score = 100.0;
            
               studentList.push_back(std1);
            
               //after you add several Student class object to the vector, then only sort them
              // by last name.
            
              return 0;
            }

            Comment

            Working...