如何在不更改原始数组的情况下对指向结构的指针数组进行排序
How do I sort array of pointers to structs without changing original array?
我对C++和指针还很陌生,非常感谢您的帮助。我正在尝试打印一个已排序的指针数组,而不更改原始的结构数组。我无法正确地对指针进行排序。我使用的是对原始数组有效的std::排序,但在指针上使用它失败了。更糟糕的是,我失败的尝试都改变了原来的样子。谢谢你抽出时间。
#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 << "studentsn";
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 studentn";
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 sortingn";
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
相关文章:
- 从函数中全局删除并重新实例化数组结构,而无需在编译时知道数组的大小
- 如何使用函数的输出初始化 const 数组结构字段?
- 传递数组结构、ofstream 和 interger 以运行
- 从文本文件中读取并输入到数组结构中,然后显示读取的数据C++
- 将文本文件读取到数组结构中
- C/C++中数组结构和数组结构的通用接口
- C++ MDC final-在字符类型的数组结构中按字母顺序对记录中的名称进行排序
- C++ 使用数组结构创建平衡的二叉搜索树
- C++:释放动态数组(结构成员)和指向此结构的指针的方法
- 使用 vector 在 c++ 中声明 3D 数组结构
- 数组结构无法正确打印
- 如何在C++中访问数组结构内部的数组结构
- CIN进入数组结构似乎什么也没输入
- ifstream将数组结构到txt文件中,然后尽可能将其提取为数组
- wlanapi-将WlanFreeMemory释放其WLAN_INTERFACE_INFO数组结构
- 显示数组结构 c++
- C++ 使用函数访问数组结构的方法是什么?
- 将庞大的数组结构复制到 GPU
- 如何封送包含字符矩阵的数组结构
- C++多维数组结构的对齐