Reputation: 91
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
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
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
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