Home » C++ programs

Sorting a structure in C++

C++ - Sorting a Structure: Here, we are going to learn how to sort a structure in C++ programming language?
Submitted by Himanshu Singh Bisht, on November 09, 2018

Generally sorting is done on an array of integer or string but there may be a situation where sorting is based on the number but actual data may be some other value.

Example:

Suppose we have to sort names of student according to roll number. So a structure can be created which can be used to store roll number and names.

Declaration of structure:

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

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




Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.