user457463
user457463

Reputation: 91

sort names by their age

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

C++ STL: Custom sorting one vector based on contents of another

Upvotes: 2

Views: 1921

Answers (5)

rashedcs
rashedcs

Reputation: 3725

You also use C++ STL pair. Then sort the pair.

Upvotes: 0

Rubber Duck
Rubber Duck

Reputation: 3037

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.

Upvotes: 0

Anthony Williams
Anthony Williams

Reputation: 68641

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);

Upvotes: 5

user122302
user122302

Reputation: 132

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

Upvotes: 0

Dennis Kempin
Dennis Kempin

Reputation: 1148

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.

Upvotes: 3

Related Questions