如何使用C++中的结构排序

239 阅读3分钟

C++中的结构化排序入门

结构是C和C++中的用户定义的数据类型。它们能够在一个名称下保存不同数据类型的数据项,这与数组不同,后者只保存相同数据类型的数据项。

前提条件

为了使本教程有所帮助,你应该有Falcon IDE或其他你能熟练使用的C++ IDE,以及一些C++的基本知识。

目标

在本教程中,我们将首先介绍结构体的基本知识,以防你对它们感到陌生,然后我们将继续学习如何使用其成员对结构体进行排序。

创建一个结构

我们使用关键字struct 来创建一个结构。

以下是结构的一般语法。

 struct struct_name
{
	//Members declaration
	type_1 member_1;
	type_2 member_2;
	.
	.
	.
	type_n member_n;
};

声明结构变量

有两种方法可以声明结构变量。

1.在结构声明过程中声明结构变量

就在结构定义的结尾处,在我们放置分号(;)之前,我们可以添加结构的可选对象名称,这些对象将用于声明该类似结构的结构对象。

例子。

using namespace std;

struct Person
{
	char name;
	int age;
}Employee,Student;

如果我们希望使用对象直接声明结构变量,那么关键字typedef也可以与结构一起使用,以定义一个新的对象,我们将在后面的 "使用结构的数组 "中看到。

2.像基本数据类型一样声明结构变量

在这种情况下,struct_name ,用来创建一个新的对象。

例子。

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

struct Person
{
	string name;
	int age;
};

int main()
{
	Person Employee;
	Person Student;
}

初始化结构成员

结构成员只能通过结构变量(对象)而不是通过声明来初始化。

这是用大括号'{}'完成的。

例子。

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

struct Person
{
	string name;
	int age;
};

int main()
{
	Person Employee = {"frank",63 };
	Person Student = {"Clare",53 };
}

或者通过使用点。

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

struct Person
{
	string name;
	int age;
}Employee,Student;

int main()
{
	Employee.name = "Frank";
	Employee.age = 63;
	
	Student.name = "Clare";
	Student.age = 53;
}

访问结构元素

通过使用点(.)也可以轻松访问结构元素,如下图所示。

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

struct Person
{
	string name;
	int age;
}Employee,Student;

int main()
{
	Employee.name = "Frank";
	Employee.age = 63;
	
	Student.name = "Clare";
	Student.age = 53;
	
	// we access the elements here using the "." and print them 
	cout << Employee.name <<" "<< Employee.age << endl ;
	cout << Student.name << " "<< Student.age;
}

输出。

Frank 63
Clare 53

处理结构体的数组

它是一个由结构体组成的数组。它可以用来存储一个结构对象的许多实例。我们将创建一个结构数组,该数组将使用 "for loops "来收集用户输入的信息,并将其显示出来。

#include <iostream>
using namespace std;

typedef struct Person
{
	string name;
	int age;
}Student;

int main()
{
	int i,n;
	cout<< "Enter number of students :";
	cin>> n;
	
	// we set the array to the number of students according to the users input
	Student s_array[n];
	
	// we prompt the user to enter input 
	cout<<"Enter Name of Student followed by age \n\n";
	// the for loop below collects the user input for the specified number of students
	for(i=0;i<n;i++){
		cout<<"________\n"; // just a line to enhance readability
		cin>>s_array[i].name;
		cin>>s_array[i].age;
	}
	
	cout<<"\nHere is the students list:\n";
	//the for loop below prints the user output in the order of entry
	for(i=0;i<n;i++){
		cout<<s_array[i].name <<"   "<<s_array[i].age <<endl;
	}
}

对结构体进行排序

现在我们已经熟悉了结构体的工作原理,让我们开始进行排序。我们将把一个人的更多属性(成员)添加到Person Struct中,使其更加实用。

除此之外,我们还将添加一个比较器函数,它将被STL的排序函数用于在我们的结构中进行排序。在我们的比较器函数中,我们决定使用哪个成员来对结构体的数组进行排序。

在我们的例子中,我们将使用年龄进行排序,通过使用小于运算符(<)从最年轻的到最老的。

bool compare( Student a, Student b){
	if(a.age < b.age)
		return 1;
	else 
		return 0;
}

要从最年长到最年轻进行排序,你应该用'>'运算符来替换'<'。如果你还想改变排序成员,你只需要在比较器函数中提到的age ,将其替换。

有趣的是,你也可以通过修改比较器函数,使其按字母顺序排序,看起来像这样。

bool compare( Student a, Student b){
	if(a.name < b.name)
		return 1;
	else 
		return 0;
}

剩下的最后一件事是调用<algorithm> 库中的sort 函数。我们将给它三个参数。

前两个只是要排序的元素范围,在本例中是结构数组的范围,第三个是比较器函数。

比如说。

sort(s_array, s_array+n, compare);

最后,我们的整个代码应该是这样的。

#include <iostream>
#include <algorithm>
using namespace std;

typedef struct Person
{
	// this are the attributes 
	string name;
	int roll_no;
	int age;
        int weight;
	
}Student;  // declare the student variable

/* our Comperator function
 (<) sorts in ascending order, replace with (>) for descending order **/

bool compare( Student a, Student b){
	/** to use another attribute for sorting, just replace 'age' with it eg. (a.roll_no < b.roll_no)
	 the return value determines which student will go first in the sorted array **/
	if(a.age < b.age)
		return 1;
	else 
		return 0;
}

int main()
{
	int i,n;
	cout<< "Enter number of students :";    // to determine the size of array
	cin>> n;
	
	// we set the array to the number of students
	Student s_array[n];
	
	cout<<"Enter Name of Student, roll number, age, and weight \n\n";
	//for loop to collect input
	for(i=0;i<n;i++){
		cout<<"---------\n";   
		cin>>s_array[i].name;
		cin>>s_array[i].roll_no;
		cin>>s_array[i].age;
		cin>>s_array[i].weight;
	}
	
	sort(s_array, s_array+n, compare);
	 /** this is the sort function
	its first & second parameter tells it the range of the array we want sorted
	and the third one is our comparator function **/
	
	cout<<"\nHere is the sorted list of Students :\n";
	//for loop to print the output
	for(i=0;i<n;i++){
		cout<<s_array[i].name <<"   " ;
		cout<<s_array[i].roll_no << "  ";
		cout<<s_array[i].age << "  ";
		cout<<s_array[i].weight << endl;
	}
}

总结

这个知识在C++中肯定有很多的应用。请随意玩弄这些代码,增加一些你自己的功能,甚至将它们应用到你的项目中。