对结构向量进行排序
Sorting a struct vector
我有一个很大的问题。.我是编程的初学者,我尝试在C 中为足球联赛排名制定一个计划,必须根据他们的分数对球队进行分类。<<<<<<<<<<<<<<<<
有人可以帮助一个想法吗?
我为具有名称和积分数的团队创建了一个结构。
我该如何对团队进行分类?对不起,我的英语不好。
这是我的代码:
#include <iostream>
#include <algorithm>
using namespace std;
//I created a struct for the team.
struct team
{
char name;
int pct;
}v[20];
int main()
{ int i,sw,aux;
for(i=1;i<=4;i++)//read the names
{
cout<<"Team "<<i<<endl;
cin>>v[i].name;
}
for(i=1;i<=4;i++)//get the points
{
cout<<"Team "<<v[i].name<<" points"<<endl;
cin>>v[i].pct;
}
//bubble sort(not working)
do
{
sw=0;
for(i=1;i<=4;i++)
{
if(v[i].pct<v[i+1].pct)
aux=v[i].pct;
v[i].pct=v[i+1].pct;
v[i+1].pct=aux;
sw=1;
}
}while(sw==1);
for(i=1;i<=4;i++)
{
cout<<v[i].pct<<endl;
}
return 0;
}
您需要像这样修改排序部分。假设您正在按desc顺序进行排序。
do
{
sw=0;
for(i=1;i<4;i++) //< not <= ,because in case of the last element you wont have any other element after it to compare
{
if(v[i].pct<v[i+1].pct) // use curly brace as you want all 4 following lines to be executed when its true
{
aux=v[i]; //swap entire struct not just one variable
v[i]=v[i+1];
v[i+1]=aux;
sw=1;
}
}
}while(sw==1);
还可能需要编辑团队名称的变量类型,因为它可以是字符串。
当您使用C 时,您可以使用一个衬里功能来对
进行排序//#include<algorithm>
//define comparator function
bool cmp(team a, team b)
{
return a.pct < b.pct;
}
sort(v+1,v+4+1,cmp);
您也可以简单地在结构内写入比较器,然后使用排序函数:
struct team
{
char name;
int pct;
bool operator<(team other) const
{
return pct > other.pct;
}
}v[20];
sort(v+1,v+4+1);
我很好奇您为什么包含算法,但不要使用任何算法。你知道STL吗?由于您包含算法,我想您可能知道一些简单的功能,例如交换,排序和复制。它们易于使用,您只需要键入一条线,而不是自己编写泡泡排序。在使用排序功能之前,应定义哪种顺序可以对这些团队生效。就像这样:
bool compareTeams(const Team &t1, const Team &t2) {
if (t1.getScore() == t2.getScore()) {
return t1.getName() < t2.getName();
}
else {
return t1.getScore() < t2.getScore();
}
}
上面的代码定义了我们考虑对团队进行分类的方向,首先,如果两个分数相等,我们首先按分数对他们进行排序,然后我们按名称对它们进行排序。最后,我们可以使用STL中现成的排序函数。现在我们定义的顺序可以使用。(我想数组V []代表团队。我对吗?(
std::sort(v, v + 20, compareTeams);
相关文章:
- 计算排序向量的向量中唯一值的计数
- 查找两个排序向量中共有的元素
- 对的排序向量 (std::vector<pair<int, int>>) 按对的第一个元素搜索并更新第二个元素值
- 如何从C++的对的排序向量中获取有关给定值的相应对
- 对象接收堆栈溢出异常 c++ 的排序向量
- "x"的所有元素都存在于"y"(排序向量)中吗?
- 指向指针排序向量的指针向量的 C++ 向量
- 未排序向量上的lower_bound/upper_bound
- 智能指针的排序向量:神秘崩溃
- 按类型排序向量并按类型或派生类型搜索
- 如何在不使用标准算法的情况下在排序向量中添加 c 元素?
- C++排序向量<double>与在<Object>双成员变量上键控的向量
- 字符串指针的排序向量
- 具有前导数字的字符串的排序向量
- 保证重新排序向量
- 结构解释的C 排序向量
- 更新排序向量的一个条目
- 通过在排序向量上使用二叉搜索来定位未排序向量中的元素
- 排序向量上 std::find_if 和 std::bind2nd 的替代品
- 使用QuickSort算法以降序排序向量