gpt4 book ai didi

c++ - 如何在不更改原始数组的情况下对指向结构的指针数组进行排序?

转载 作者:行者123 更新时间:2023-11-28 06:37:56 25 4
gpt4 key购买 nike

我对 C++ 和指针相当陌生,非常感谢任何帮助。我试图在不更改原始结构数组的情况下打印一个排序的指针数组。我无法正确排序指针。我正在使用在原始数组上工作的 std::sort,但我无法在指针上使用它。更糟糕的是,我失败的尝试全部改变了原来的。感谢您的时间。

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <string.h>

using namespace std;

struct Student
{
int age;
char name[30];

};

void displayStudent(Student s)
{

cout << endl<< s.age<< " "<< s.name;

}


int main()
{
Student s1;
s1.age = 10;
strcpy(s1.name, "Guy");

Student s2;
s2.age = 33;
strcpy(s2.name, "Buddy");

Student s3;
s3.age = 16;
strcpy(s3.name, "Friend");

Student s4;
s4.age = 55;
strcpy(s4.name, "Pal");

Student myClass[4];
myClass[0] = s1;
myClass[1] = s2;
myClass[2] = s3;
myClass[3] = s4;

Student *myClassPt;
myClassPt = &myClass[0];
Student *SBN[4];
Student *SBG[4];
Student *SBA[4];
for (int i = 0; i < 4; i++)
{
SBN[i] = &(myClassPt[i]);
SBA[i] = &(myClassPt[i]);

}
cout << "Original" << endl;
for (int i = 0; i < 4; i++)
{
displayStudent(myClass[i]);
}

std::sort(*SBN, *SBN + 4, [](Student &a, Student &b){ return a.name < b.name; });
std::sort(*SBA, *SBA + 3, [](Student const &a, Student const &b){ return a.age < b.age; });

cout <<endl<<endl<< "Sorted by name" << endl;
for (int i = 0; i < 4; i++)
{
displayStudent(*SBN[i]);
}
cout << endl << endl << "Sorted by age" << endl;
for (int i = 0; i < 4; i++)
{
displayStudent(*SBA[i]);
}

cout << endl <<endl<< "Original" << endl;
for (int i = 0; i < 4; i++)
{
displayStudent(myClass[i]);
}

return 0;
}

最佳答案

您似乎想根据指针所指向的对象对指针进行排序。所以你需要根据指针指向的对象对指针进行排序,而不是试图直接对它们指向的对象进行排序:

std::sort(SBN, SBN + 4, [](const Student* a, const Student* b)
{ return a->name < b->name; });

这是一个工作示例:

#include <iostream>
#include <algorithm>

struct student { int age; };

int main()
{
student ss[] = { {23}, {12}, {42}, {9}};
std::cout << "students\n";
for (const auto& s : ss) std::cout << s.age << " ";
std::cout << std::endl;

student* ps[] = { &ss[0], &ss[1], &ss[2], &ss[3]};
std::cout << "pointers to student\n";
for (auto p : ps) std::cout << p->age << " ";
std::cout << std::endl;

std::sort(ps, ps + 4, [](const student* a, const student* b)
{ return a->age < b->age;});
std::cout << "pointers to student after sorting\n";
for (auto p : ps) std::cout << p->age << " ";
std::cout << std::endl;
}

输出:

students
23 12 42 9
pointers to student
23 12 42 9
pointers to student after sorting
9 12 23 42

关于c++ - 如何在不更改原始数组的情况下对指向结构的指针数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26479846/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com