c++ - 在 C++ 中对结构进行排序

标签 c++ arrays sorting structure

我想使用结构对数组进行排序(我第一次使用结构)。这个结构获取一些学生的名字和 ID 号,问题是它显示其他名字而不是显示名字(我使用 dev C++)

#include<iostream>
#include<fstream>
#include<conio.h>
#include <sstream>
using namespace std;
struct Student
{
  long long int ID;
  string FirstName,LastName;
} mystudent[100];
void PrintInformation(Student sEmployee[100],int b)
{
    for(int i=0;i<b;i++)
    {
            cout << "First Name:   " << sEmployee[i].FirstName<< endl;
            cout << "ID:  " << sEmployee[i].ID<< endl;
            }
}
void Sort (Student mine);
int main ()
{
   int n, c, d, temp;
   cout << "Enter element: ";
   cin>>n;
   for(int i=0;i<n;i++) 
   {
    cout << "Enter FirstName "<<i+1<<": ";
    cin>>mystudent[i].FirstName;
   } 
  for(int i=0;i<n;i++) 
   {
    cout << "Enter ID "<<mystudent[i].FirstName<<": ";
    cin>>mystudent[i].ID;
   }
  for (int i = 1 ; i <= n - 1; i++) 
  {
    d = i;
    while ( d > 0 && mystudent[i].ID < mystudent[i-1].ID)
     {
      temp         = mystudent[i].ID;
      mystudent[i].ID   = mystudent[i-1].ID;
      mystudent[i-1].ID = temp;
      mystudent[i-1].FirstName=mystudent[i].FirstName;
      d--;
    }
  }
  cout<<"Sorted list in ascending order:\n";

  PrintInformation(mystudent,n); 
   getch();
   return 0; 
}

最佳答案

这段代码:

  temp         = mystudent[i].ID;
  mystudent[i].ID   = mystudent[i-1].ID;
  mystudent[i-1].ID = temp;
  mystudent[i-1].FirstName=mystudent[i].FirstName;

交换 ID , 但复制 FirstName .更糟糕的是,它对 LastName 没有任何作用。 .

改为尝试:

struct Student tempstudent = mystudent[i] ;
mystudent[i]= mystudent[i-1] ;
mystudent[i-1]= tempstudent ;

或者更好的是,使用 STL。

#include <utility>

std::swap(mystudent[i], mystudent[i-1]) ;

请注意,swap<algorithm>如果您是 C++11 之前的用户。

关于c++ - 在 C++ 中对结构进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21011961/

相关文章:

ios - 俱乐部对象数组

ruby - 按值对哈希进行排序时如何保留键的字母顺序

android - 具有优先级 ID 和日期时间的排序列表模型

c++ - 力扣#15 : 3sum -- avoiding duplicate

arrays - 在 PostgreSQL 中索引自定义范围类型的数组

c++ - 如何使用 CMake 将 .pdbs 链接到项目?

c++ - STM32 从 PC 通过 USB float ,endianess 挣扎

c++ - 段。 std::unique_ptr 和 ctor 的错误

c++ - C++ 中没有提升的语音识别或 msconfig

ios - 快速转换通用数组会导致 fatal error