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

如何用toml++将TOML数组转换为C++ vector<int>用于MPI传输?

问题:将TOML数组转换为C++ vector(适配MPI传输)

我的TOML文件内容如下:

[Calculator_parameters]
dontVary = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

我需要用toml++把这个数组转换成可通过MPI传输的vector<int>,但尝试的代码出现类型不匹配问题,代码如下:

#include <iostream>
#include <fstream> // Include for file stream operations
#include "toml.hpp"
#include <vector>
#include <unordered_map>
#include <string>
using namespace std;

int main(int argc, char* argv[])
{
    toml::table tbl;
    tbl = toml::parse(file);  // file是用户输入的字符串,这部分没问题
    ...
    auto dontVary_array = tbl["Calculator_parameters"]["dontVary"];  
    vector<int> dontVary;
    if (toml::array* arr = dontVary_array.as_array()) {
        arr->for_each([&dontVary](auto&& el)
        {
            if (const auto* int_elem = el.as_integer())
                dontVary.push_back((int)(*int_elem));          //这里出现类型不匹配?         
            else
                cerr << "Error: Element is not an integer." << endl;
        });
    // 代码未完整,但问题出在上述转换部分
}

解决方案

问题根源是toml::integer的类型处理:toml++中as_integer()返回的是toml::integer类型指针,该类型本质是64位整数(通常为int64_t),直接用(int)强转可能触发编译器类型检查错误,尤其是在严格编译模式下。以下是三种可行的解决方式:

方式1:使用value_or安全转换

利用toml++提供的value_or方法直接获取int值,同时处理转换失败的情况:

auto dontVary_array = tbl["Calculator_parameters"]["dontVary"];
vector<int> dontVary;
if (const auto* arr = dontVary_array.as_array()) {
    dontVary.reserve(arr->size()); // 预分配空间提升效率
    for (const auto& elem : *arr) {
        try {
            // 尝试转换为int,失败时返回默认值-1(可按需修改)
            dontVary.push_back(elem.value_or<int>(-1));
        } catch (const toml::type_error& e) {
            cerr << "元素转换失败: " << e.what() << endl;
        }
    }
}

方式2:显式转换并添加溢出检查

保留原有的指针判断逻辑,显式转换toml::integer到int,同时检查数值是否超出int范围:

arr->for_each([&dontVary](auto&& el)
{
    if (const auto* int_elem = el.as_integer()) {
        // 检查数值是否在int的有效范围内
        if (*int_elem > INT_MAX || *int_elem < INT_MIN) {
            cerr << "错误:整数超出int类型范围" << endl;
            return;
        }
        dontVary.push_back(static_cast<int>(*int_elem));
    } else {
        cerr << "错误:元素不是整数类型" << endl;
    }
});

方式3:直接构造vector(最简洁)

toml++支持直接将数组转换为std::vector,无需手动遍历,自动处理类型检查和转换:

try {
    vector<int> dontVary = tbl["Calculator_parameters"]["dontVary"]
                            .as_array()->to<std::vector<int>>();
} catch (const toml::exception& e) {
    cerr << "转换失败: " << e.what() << endl;
}

转换失败时会抛出toml::type_error或toml::conversion_error异常,适合大多数场景。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 20:35:33