C++结构体数组sort换位置
时间: 2024-12-20 15:16:40 浏览: 35
在C++中,如果你有一个结构体数组,并想要对它们的某个成员变量进行排序,通常你会先定义一个比较函数,然后利用`std::sort`函数。假设你有一个名为`Person`的结构体,包含姓名`name`和年龄`age`,你可以这样做:
```cpp
#include <algorithm>
#include <string>
// 定义Person结构体
struct Person {
std::string name;
int age;
};
// 比较函数,用于按年龄排序
bool compareByAge(const Person &a, const Person &b) {
return a.age < b.age;
}
// 结构体数组
Person people[] = {{"Alice", 25}, {"Bob", 30}, {"Charlie", 20}};
// 使用sort函数对年龄进行升序排列
void swapPositions(Person *begin, Person *end) {
std::sort(begin, end, compareByAge);
}
int main() {
// 调用swapPositions并打印排序后的结果
for (Person &person : people) {
std::cout << person.name << ": " << person.age << "\n";
}
return 0;
}
```
在这个例子中,`swapPositions`函数不是交换数组元素的位置,而是直接通过`std::sort`改变了数组中元素的顺序(这里是按年龄升序)。如果你想交换年龄排序后的名字和对应的新位置,你需要遍历排序后的数组并在适当的地方做这样的操作。
阅读全文
相关推荐


















