2

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

Community
  • 1
  • 1
user457463
  • 91
  • 1
  • 1
  • 6
  • 6
    What bugs does this program have? What is the expected output and what output do you get? Have you tried attaching a debugger to see where the code is going wrong? "Here is my code, please fix it" is not an appropriate question here on Stack OVerflow; try instead for something along the lines of "I'm trying to do X, but when I run it with input Y I unexpectedly get result Z; I think it might have something to do with W." – James McNellis Sep 24 '10 at 15:32

5 Answers5

5

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
  • 66,628
  • 14
  • 133
  • 155
3

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
  • 1,138
  • 2
  • 13
  • 19
  • no i want like this array of names and their ages and sort names using their ages – user457463 Sep 24 '10 at 15:37
  • 1
    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 Sep 24 '10 at 15:42
0

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

user122302
  • 132
  • 5
0

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.

Rubber Duck
  • 2,997
  • 2
  • 20
  • 25
0

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

rashedcs
  • 3,588
  • 2
  • 39
  • 40