MST

星途 面试题库

面试题:C语言联合体数组在复杂数据结构中的优化设计

假设有一个复杂的数据结构,其中包含一个联合体数组作为成员。联合体中有不同类型的成员,如整数、浮点数和结构体指针。该数据结构用于表示不同类型的节点,并且这些节点需要按照特定的规则进行排序(例如,根据节点的某种属性值排序)。请设计这个复杂的数据结构,并实现对联合体数组成员进行排序的算法,同时要考虑内存管理和效率优化,给出完整的代码实现。
13.1万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试
#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;
}
  1. 联合体定义NodeValue联合体包含了intfloatvoid*类型的成员,用于表示不同类型的数据。
  2. 节点结构体定义Node结构体包含了联合体成员value,类型标识type,以及用于排序的属性值sortAttribute
  3. 比较函数compareNodes函数根据sortAttribute对节点进行排序。
  4. 内存释放函数freeNodeMemory函数用于释放节点中的动态分配内存,这里由于structPtr没有具体类型,只是打印了提示信息。实际应用中需要根据具体类型实现内存释放逻辑。
  5. 主函数:在main函数中创建了一些示例节点,进行排序并输出结果,同时调用内存释放函数。