Q:

Sorting a structure in C++

belongs to collection: C++ programs on various topics

0

Sorting a structure in C++

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

C++ Code to sort structure:

#include <bits/stdc++.h>
using namespace std;

typedef struct value{
	int roll;
	string name;
}data;

bool compare(data a, data b)
{
	//for descending order replace with a.roll >b.roll
	if(a.roll < b.roll)		
		return 1;
	else
		return 0;
}

int main()
{
	int n,i;

	cout<<"Enter the number of students\n";
	cin>>n;	

	data  array[n];//array of structure is created

	cout<<"Enter roll number and then name\n";
	for(i=0;i<n;i++)
	{
		cin>>array[i].roll;
		cin>>array[i].name;
	}

	sort(array,array+n,compare);

	cout<<"Sorted list..."<<endl;
	for(i=0;i<n;i++)
	{
		cout<<array[i].roll<<" ";
		cout<<array[i].name<<endl;
	}

	return 0;
}

Output

 
Enter the number of students
3
Enter roll number and then name
101 Amit
102 Abhishek
103 Shubham
Sorted list...
101 Amit
102 Abhishek
103 Shubham

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C++ programs on various topics

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C++ program to multiply two numbers without using ... >>
<< C++ program to find Sum of cubes of first N Even n...