所以我想按不同的标准对数组进行排序,但问题来了,当两个项目具有相同的值时,我想按名称排序。让我用一个例子来解释它: 我有这个:
俄亥俄州 49
威斯康星州 46
肯塔基州 46
这将是我的数据结构:
const int US_STATES = 51;
const int MAX_INFO = 5;
struct Info{
double values;
int units, shipments;
};
typedef Info TaulaQuarters[MAX_INFO]; //Where TaulaQuarters[0] és el total i TaulaQUarters[1..4] son els trimestres
struct Estat{
string stateName,code;
int population;
TaulaQuarters taulaQuarters;
int totalPopulation;
};
typedef Estat TaulaEstats[US_STATES];
因此,威斯康星州和肯塔基州具有相同的值(value),但我希望威斯康星州位于肯塔基州之下,因为肯塔基州按字母顺序大于威斯康星州。 让我向您展示我的主要排序操作:
bool esMajor (double n1, double n2, string nom1, string nom2, char criteri)
{
//pre:
//lpost:
int enter1 = int(n1);
int enter2 = int(n2);
bool hoEs = false;
if (criteri == 'v'){
if (n1 > n2) hoEs = true;
else if (n1 == n2){
if (nom1 > nom2) hoEs = true;
}
}
else if (criteri == 'u' or criteri == 's'){
if (enter1 > enter2) hoEs = true;
else if (enter1 == enter2){
if (nom1 < nom2) hoEs = true;
}
}
else if (criteri == 'n'){
if (nom1 < nom2) hoEs = true;
}
//else if ()
return hoEs;
}
void ordena (TaulaEstats taulaEstats, char criteri)
{
//Pre:
//post:
//----Intializing----
Estat aux; aux.code = "--"; aux.population = 0; aux.stateName = "--"; aux.totalPopulation = 0;
for (int x = 0; x < 5; x++){
aux.taulaQuarters[x].shipments = 0; aux.taulaQuarters[x].units = 0; aux.taulaQuarters[x].values = 0;
}
//-------END---------
for (int i = 0; i < int(US_STATES);i++){
int j = i;
//if (criteri == 'v'){
while (j > 0 and esMajor(taulaEstats[j].taulaQuarters[0].values,taulaEstats[j-1].taulaQuarters[0].values,taulaEstats[j].stateName, taulaEstats[j-1].stateName, criteri)){
aux = taulaEstats[j-1];
taulaEstats[j-1] = taulaEstats[j];
taulaEstats[j]= aux;
j--;
}
}
}
esMajor
会根据标准告诉我,如果第一个数字大于第二个,如果相等,会告诉我名字是否大于第二个.
ordena
就是我必须对数组进行排序的算法。
感谢您的帮助,祝您节日快乐!!
(抱歉我的英语不好)。
最佳答案
如果这是 C++,您应该将数字和名称封装在您的结构中,并为您的类重载比较运算符。像这样:
struct StateInfo
{
std::string stateName;
int stateNumber;
public:
StateInfo() : stateName("DEFAULTNAME"),stateNumber(0){}
StateInfo(std::string name, int, number): stateName(name),stateNumber(number){}
bool operator< (const StateInfo& rhs)
{
if( rhs.stateNumber==this->stateNumber)
{
return rhs.stateName< this->stateName; //if numbers are equal compare by name
}
return rhs.stateNumber<this->stateNumber;
}
//overload other operators as necessary
}
现在您可以使用 std::sort
来自 #include <algorithm>
对您放入容器中的所有对象进行排序,例如 std::vector
.
解决方案的要点是让 std::sort 知道如何比较结构的 2 个不同实例。当 std::sort 知道这一点时,它可以为您进行排序。
走数组路线很乱,不推荐。
如果您有兴趣制作自己的排序算法或练习插入排序、合并排序、快速排序等,那么您仍然可以使用重载运算符 > < == <= 和 >= 来编写自己的排序算法。
关于c++ - 数组中的错误功能排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34373769/