#include <iostream>
#include <vector>
#include <algorithm>
// 定义联合体
union NodeValue {
int intValue;
float floatValue;
void* structPtr;
};
// 定义节点结构体
struct Node {
int type; // 0: int, 1: float, 2: structPtr
NodeValue value;
// 假设这里有一个通用的属性值用于排序,这里简单用int表示
int sortAttribute;
Node(int t, NodeValue v, int attr) : type(t), value(v), sortAttribute(attr) {}
};
// 比较函数,根据sortAttribute进行排序
bool compareNodes(const Node& a, const Node& b) {
return a.sortAttribute < b.sortAttribute;
}
// 释放内存函数,这里由于structPtr没有具体类型,简单打印提示
void freeNodeMemory(Node& node) {
if (node.type == 2) {
std::cout << "Need to free structPtr memory, but type is not known precisely." << std::endl;
}
}
int main() {
// 创建节点向量
std::vector<Node> nodes;
// 示例数据
NodeValue value1;
value1.intValue = 10;
nodes.emplace_back(0, value1, 3);
NodeValue value2;
value2.floatValue = 3.14f;
nodes.emplace_back(1, value2, 1);
NodeValue value3;
value3.structPtr = nullptr;
nodes.emplace_back(2, value3, 2);
// 排序
std::sort(nodes.begin(), nodes.end(), compareNodes);
// 输出排序结果
for (const auto& node : nodes) {
std::cout << "Sort Attribute: " << node.sortAttribute << ", Type: " << node.type << std::endl;
freeNodeMemory(const_cast<Node&>(node));
}
return 0;
}
- 联合体定义:
NodeValue
联合体包含了int
、float
和void*
类型的成员,用于表示不同类型的数据。
- 节点结构体定义:
Node
结构体包含了联合体成员value
,类型标识type
,以及用于排序的属性值sortAttribute
。
- 比较函数:
compareNodes
函数根据sortAttribute
对节点进行排序。
- 内存释放函数:
freeNodeMemory
函数用于释放节点中的动态分配内存,这里由于structPtr
没有具体类型,只是打印了提示信息。实际应用中需要根据具体类型实现内存释放逻辑。
- 主函数:在
main
函数中创建了一些示例节点,进行排序并输出结果,同时调用内存释放函数。