tags:

views:

130

answers:

4

i want so sort names by their ages

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

struct Person{
 std::string name;
 int age;
};

struct by_age{
  bool operator() (Person  const &a,Person const &b){
   return a.age>b.age;    
  }
};

int main(){
 vector<Person>people;
  for (int i=0;i<4;i++){
   cin>>people[i].age>>people[i].name;
  }

  sort(people.begin(),people.end(),by_age());
   for (int i=0;i<4;i++){
    cout<<people[i].name<<people[i].age<<" ";
   }    
 return 0;
}

but this code has many bugs please help look at this site

http://stackoverflow.com/questions/1723066/c-stl-custom-sorting-one-vector-based-on-contents-of-another

+3  A: 

You need to initialize the vector to tell it how many elements it should contain.

vector<Person> people(4);

Besides that, please describe the "bugs" so people can help you.

Dennis Kempin
no i want like this array of names and their ages and sort names using their ages
As far as I can see this is something that you are lacking a lot of background knowledge for. That can't be explained easily here.If you are working with a tutorial or book try to go back a few chapters and study the basics.
Dennis Kempin
A: 

Put the ages in a multimap and they will be sorted for you.

+5  A: 

The main problem with this code is that the vector is empty, so when you set the values you are corrupting memory. You either need to set the vector size explicitly, or use push_back() to add values to it:

 vector<Person> people(4);
Anthony Williams
You can also use `people.push_back(Person(name, age));` inside the loop.
André Caron
A: 

Instead of trying to use a sort that is already made for you, look into a bubble sort. It's inefficient, however it's the first sort everyone learns.

As a note, when you have 'using namespace std' you do not need the 'std' in front of any code.

Vurk