Sorting Alphabetically ??

Hi, I needed some help with something I have been trying to code.
So the program I want to make asks for a number of people. Then the
user enters the names of these people.

What I am having trouble with doing, is sorting these names alphabetically.
eg. If person[0] = joe, and person [1] = bob, I want to make it so that
person [0] is bob, and person [1] = joe. Im not really sure how to go about this ...

This is my first time on this website, so please bare with my lack of C++ knowledge :/

Any help would be greatly appreciated :)

#include <cstdlib>
#include <string>
#include <iostream>
#include <cmath>

using namespace std;
struct people
{
string name;
};


int main()
{
int numberOfPeople;
people person[];

cout << "Enter the number of people: ";
cin >> numberOfPeople;

cout << "Enter the last name of a person, then press 'Enter'";
for (int count = 0; count > numberOfPeople; count++)
{
cin >> person[count].name;
}

}
you are missing a new (and delete) function:
person is only a pointer!
about sorting:
there are different strategies.
The easiest to implement (not the best in terms of performances) might be the old fashion bubble sort. Google it!
Another ingredient missing is string comparison (there is a function for that: search the std::string class)
And don't forget you might want to swap elements!
I would suggest to use std::string for storing each name and std::vector for storing the names.

Then you can use
1
2
#include <algorithm>
sort(iterator first, iterator last)
to sort them.
As an aside, re general naming of variables, types - using logical naming really helps in understanding code.

Your choice of name for your people struct and person array is somewhat backwards/illogical.
The struct represents a single person, so you should call that 'person', and the array represents a list of people, so you should call that 'people', giving you:
1
2
3
4
struct person
{
  string name;
};


and person people[]; (although that won't compile - you need to initialise the content).

Oh, and person (or people in this new code) isn't a pointer as samusamu says, it's an array of actual object instances, so don't worry about new/delete.

Cheers,
Jim
Topic archived. No new replies allowed.