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

C++中二维vector转torch::tensor数据异常问题求助

问题分析

你的问题核心在于二维std::vector<std::vector<int>>的内存并非连续存储:每个子vector都是独立分配的内存块,indx1.data()返回的是指向这些子vector对象的指针数组,而非直接指向底层的int数据。而torch::from_blob要求输入的是连续的原始数据指针,直接传入会读取错误的内存地址,导致输出乱码。

解决方案

以下是两种可靠的修复方式:

方式1:转为一维连续vector后再创建tensor

先把分散的int数据拷贝到连续的一维容器中,再用from_blob生成tensor:

std::vector<std::vector<int>> indx1 = {{126, 22}, {166, 102}, {46, 46}, {166, 54}};
// 构建连续的一维vector
std::vector<int> flat_indx;
flat_indx.reserve(indx1.size() * 2);
for (const auto& row : indx1) {
    flat_indx.insert(flat_indx.end(), row.begin(), row.end());
}
// 创建tensor
auto indx_options = torch::TensorOptions().dtype(torch::kInt32);
auto indx = torch::from_blob(flat_indx.data(), {indx1.size(), 2}, indx_options);
// 若需要tensor拥有独立内存(不依赖原vector生命周期),可调用clone()
// auto indx = torch::from_blob(flat_indx.data(), {indx1.size(), 2}, indx_options).clone();

方式2:直接使用LibTorch嵌套构造函数

LibTorch支持直接从嵌套vector创建tensor,自动处理内存连续性问题,代码更简洁:

std::vector<std::vector<int>> indx1 = {{126, 22}, {166, 102}, {46, 46}, {166, 54}};
auto indx = torch::tensor(indx1, torch::kInt32);
验证结果

两种方式生成的tensor输出均符合预期:

126   22
 166  102
  46   46
 166   54
[ CPUIntType{4,2} ]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 09:42:36