Sorting arrays alphabetical
Feb 25, 2014 at 3:25am UTC
I need to sort the array alphabetically but I really do not how. I tried to do it below but it didn't work.Any help is appreciated.
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
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void sort(ifstream& infile){
int number;
infile>>number;
string firstname,lastname,birthdate;
string firstname1[number],lastname2[number],birthdate3[number];
//each line has 3 pieces of info. Was read successful?
for (int i=0; i<number; i++){
infile>>firstname1[i]>>lastname2[i]>>birthdate3[i];
cout<<firstname1[i]<<" " <<lastname2[i]<<" " <<birthdate3[i]<<endl;
}
string temp[number];
for (int l=0; l<number; l++)
{
if (firstname1[l]>firstname1[l+1])
{
temp[l] += firstname1[l];
}
else
temp[l]+=firstname1[l+1];
cout<<temp[l]<<endl;
}
}
int main (){
string infile_name;
ifstream infile;
cout << "What file?" ;
cin>>infile_name;
infile.open(infile_name.c_str());
sort(infile);
}
Feb 25, 2014 at 3:27am UTC
If you have an array, you can just use std::sort(). What exactly are you doing in your code that isn't working?
Feb 25, 2014 at 3:29am UTC
Well I want it to output to the user and it when I do that it doesn't output them in the order I need them to. How would I use the std::sort()?
Feb 25, 2014 at 3:30am UTC
Also I they are parallel arrays so when I sort the names I need to be able to output the birthdate and last name along with it
Feb 25, 2014 at 3:35am UTC
Ugh, parallel arrays. I hope it is a requirement of your assignment that is giving you that, otherwise I would suggest simply making an array of structures and sorting that with std::sort().
alyssnyx wrote:it doesn't output them in the order I need them to.
That doesn't really elaborate at all. You have effectively said "it doesn't work." What part isn't working? The variable declaration syntax? The loop syntax? The loop body code itself?
Last edited on Feb 25, 2014 at 3:35am UTC
Feb 25, 2014 at 3:51am UTC
Okay I changed up the code a bit
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
int index[number];
for (int i=0;i<number-1;i++){
index[i]=i;
}
for (int l=0; l<number-1; l++)
{ int temp=0;
for (int j=l+1; j<number-1;j++){
if (firstname1[index[l]]>firstname1[index[j]])
{
temp = index[l];
index[l]=index[j];
index[j]=temp;
}
}
}
for (int i=0;i<=number-1;i++){
cout<<firstname1[index[i]]<<endl;
}
I really don't know how to do what you were talking about, but right now it sorts everything except the last element and then crashes. Any idea for what is wrong?
Feb 25, 2014 at 3:54am UTC
Nevermind I got it, thank you for your reply though!
Topic archived. No new replies allowed.