C++ 排序类数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12823573/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 16:39:10  来源:igfitidea点击:

C++ Sorting Class Array

c++

提问by baoky chen

C++ Sorting Array Class

C++ 排序数组类

I have an array object that record the following..

我有一个记录以下内容的数组对象..

This is at classone.h

这是在classone.h

ClassOne
{
string name;
int data;
float valueData;
}

and the constructor are created at classone.cpp

并且构造函数是在classone.cpp创建的

At main.cpp I created ClassOne Array of Size 10

在 main.cpp 我创建了 ClassOne Array of Size 10

#include "classone.h"

ClassOne cone[10];

Next is i recorded several value to the object

接下来是我向对象记录了几个值

and now ClassOne got 3 objects

现在 ClassOne 有 3 个对象

cone[0]
name = "hello"
data = 1
valueData = 20

cone[1]
name = "panda"
data = 2
valueData = 15

cone[2]
name = "joe"
data = 3
valueData = 25

What i want to achieve is do a sort that can rearrange this array by valueDatahighest ascending form so.. it will be

我想要实现的是进行一种排序,可以按valueData最高升序形式重新排列此数组,因此..它将是

cone[2]then cone[0]then cone[1]..

cone[2]然后cone[0]然后cone[1]..

but the issue if i use bubble sort , i tried google and find some, they are sorting by e.g int a[]={9,6,5,23,2,6,2,7,1,8};

但是如果我使用冒泡排序的问题,我尝试了谷歌并找到了一些,他们正在按例如排序 int a[]={9,6,5,23,2,6,2,7,1,8};

but i wanna sort by class array object. and re-arrange the value together , how do i achieve this.

但我想按类数组对象排序。并将值重新排列在一起,我如何实现这一点。

So when i cout it will be

所以当我 cout 它会

-- Highest to lowest --
1) Name: Joe , Data = 3, Value =25
2) Name: Hello , Data =1 , Value = 20
3) Name: Panda, Data = 2, Value = 15

Thanks for all help and guide!!

感谢大家的帮助和指导!!

回答by Kerrek SB

The easiest way is to use the standard library:

最简单的方法是使用标准库:

#include <algorithm>

std::sort(cone, cone + 10,
          [](ClassOne const & a, ClassOne const & b) -> bool
          { return a.value < b.value; } );

If you're willing to define a comparison operator globally, you don't even need the lambda:

如果您愿意全局定义比较运算符,则甚至不需要 lambda:

bool operator<(ClassOne const & a, ClassOne const & b)
{
    return a.value < b.value;
}

std::sort(cone, cone + 10);

Or you could make the comparator a member function. Or you could give the comparator function a custom name and pass that as the third argument of sort. This might be a good idea in the case where the comparison is specific to your situation and not "natural":

或者您可以使比较器成为成员函数。或者您可以为比较器函数指定一个自定义名称并将其作为sort. 在比较特定于您的情况而不是“自然”的情况下,这可能是一个好主意:

bool ValueCmp(ClassOne const & a, ClassOne const & b)
{
    return a.value < b.value;
}

std::sort(cone, cone + 10, ValueCmp);

The last version is useful if you don't have C++11 support (for lambdas, as in the first case), or if you want to reuse the comparator in multiple different situations.

如果您没有 C++11 支持(对于 lambda,如第一种情况),或者您想在多种不同情况下重用比较器,则最后一个版本很有用。

回答by juanchopanza

Use std::sortand a suitable sort function/functor:

使用std::sort和合适的排序函数/函子:

bool comp(const ClassOne& lhs, const ClassOne& rhs)
{
  return lhs.valueData < rhs.valueData;
}

std::sort(cone, cone+10, comp);

or, in C++11,

或者,在 C++11 中,

std::sort(std::begin(cone), std::end(cone), comp);

回答by DaRkViRuS

You can make a struct that implements the operator <method that std::sortin the <algorithm>header uses to sort iterated items.

你可以做一个结构,它实现的operator <方法是std::sort<algorithm>标题上使用到某种重复项目。

struct One {
string name;
int data;
float valueData;

bool operator < (const one &a) const{
return valueData <a.valueData;
}

};

then all you have to do is to make an array of this struct and sort it using the sort function

那么你所要做的就是创建一个这个结构的数组并使用 sort 函数对其进行排序

回答by Benjamin Lindley

Look at your Bubble sort source. At some point, it will be comparing one intto another, probably with either the less than operator (<) or the greater than operator (>). That's where the sort function determines the relative order of those two items. By repeating that comparison many times, the sort function is able to determine the total order of the collection.

查看您的冒泡排序源。在某些时候,它会比较一个int与另一个,可能使用小于运算符 (<) 或大于运算符 (>)。这就是 sort 函数确定这两个项目的相对顺序的地方。通过多次重复该比较,排序函数能够确定集合的总顺序。

You need to replace that operation with your own comparison function. A function that takes two objects of your class, and returns true if the first should be considered less than the second, false if the second should be considered less than the first, and false if they should be considered equivalent.

您需要用您自己的比较函数替换该操作。一个函数,它接受你的类的两个对象,如果第一个被认为小于第二个,则返回 true,如果第二个被认为小于第一个,则返回 false,如果它们被认为是等效的,则返回 false。

回答by Adam

You must define a comparison operator for your class. How you determine whether one object is less than another isn't clear from your question.

您必须为您的类定义一个比较运算符。您的问题不清楚您如何确定一个对象是否小于另一个对象。

回答by Nalini

Try this ... ....

尝试这个 ... ....

     void ClassOne::sort(ClassOne *obj,int n)       
     {
      ClassOne temp;
      int i, j;
      for (i = 0; i < n; i++)
      for (j = n - 1; j > i; j--)
        if (obj[j].valueData <obj[j - 1].valueData )
           {
            temp = obj[j];
            obj[j] = obj[j - 1];
            obj[j - 1] = temp;
         }
         }
     ...
      int main()
      {
     ClassOne obj[3],a;
        for(int i=0;i<3;i++)
         obj[i].readdata();
        a.sort(obj,3);
        ...
  }