You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用C++17的std组件高效读取配置文件完整动画参数

修改方案:读取动画路径及帧参数到std::unordered_map(C++17兼容)

原来的std::unordered_map仅存储动画路径,现在需要扩展为存储包含路径、帧数、帧宽、帧高的完整动画信息,保持使用std::unordered_map保证查询性能,所有实现严格兼容C++17标准。


1. 定义动画信息结构体

用聚合结构体存储所有动画参数,C++17支持直接聚合初始化,无需手动编写构造函数:

struct AnimationInfo {
    std::string path;
    int frame_count;
    int frame_width;
    int frame_height;
};

2. 修改LoadPaths函数

调整函数参数中的map类型,将value改为AnimationInfo,并在读取时填充完整参数:

#include "GetPath.h"

#include <fstream>
#include <sstream>
#include <unordered_map>
#include <string>

struct AnimationInfo {
    std::string path;
    int frame_count;
    int frame_width;
    int frame_height;
};

void LoadPaths(const std::string& l_pathFile, std::unordered_map<std::string, AnimationInfo>& m_animations)
{
    std::string percorso = GetWorkingDirectory();
    std::ifstream paths(percorso + l_pathFile);

    if (!paths.is_open()) {
        std::cerr << "! Failed loading the path file: " << percorso + l_pathFile << std::endl;
        return;
    }

    m_animations.clear();

    std::string line;
    while (std::getline(paths, line)) {
        std::stringstream keystream(line);
        std::string anim_id;
        AnimationInfo info;

        // 按格式读取所有字段,添加格式校验
        if (keystream >> anim_id >> info.path >> info.frame_count >> info.frame_width >> info.frame_height) {
            // 使用emplace+std::move减少拷贝,提升性能
            m_animations.emplace(std::move(anim_id), std::move(info));
        } else {
            std::cerr << "! Invalid line format: " << line << std::endl;
        }
    }

    paths.close();
}

优化说明:

  • 简化文件打开逻辑,直接在构造时初始化std::ifstream
  • 用clear()替代原有的空元素初始化,避免多余操作
  • 添加格式错误提示,便于调试
  • 使用std::move转移字符串所有权,减少内存拷贝开销(C++17支持)

3. 修改main函数适配新结构

更新map类型,查询后可直接获取所有动画参数:

#include "GetPath.h"
#include "LoadPaths.h"

#include <string>
#include <iostream>
#include <unordered_map>

struct AnimationInfo {
    std::string path;
    int frame_count;
    int frame_width;
    int frame_height;
};

int main()
{
    std::unordered_map<std::string, AnimationInfo> m_animations;

    LoadPaths("texture.cfg", m_animations);

    auto it = m_animations.find("plyRun");
    if (it != m_animations.end()) {
        const auto& info = it->second;
        std::cout << "路径: " << info.path << "\n";
        std::cout << "帧数: " << info.frame_count << "\n";
        std::cout << "帧宽: " << info.frame_width << "\n";
        std::cout << "帧高: " << info.frame_height << "\n";
    } else {
        std::cout << "未找到动画: plyRun\n";
    }

    return 0;
}

建议将AnimationInfo的定义放在LoadPaths.h头文件中,避免重复定义。

4. 性能与兼容性说明

  • 使用std::unordered_map保证O(1)平均查询性能,满足性能要求
  • 所有代码兼容C17:聚合结构体初始化、std::move语义、emplace方法均为C17完全支持的特性
  • 读取时直接按字段解析,避免多余内存分配,提升加载效率

内容的提问来源于stack exchange,提问作者user20420531

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 12:15:36