c++ - 整数数组到向量
问题描述
我正在尝试将一个int 数组添加到一个 vector中。无论我做什么,调试器都会指示新的向量元素只是“0”。
std::vector< int * > level_collection;
for( auto & i : levels )
{
auto size = std::get< 1 >(i).size();
int level_data[size];
for( size_t x = 0; x < size; x ++ )
{
level_data[x] = std::get< 1 >(i)[x];
}
for( auto x : level_data)
{
std::cout << x << std::endl; // This works. All the values print correctly. So it did store the information as it should.
}
level_collection.push_back( level_data );
}
for( auto & i : level_collection)
{
std::cout << i[1] << std::endl; // This prints ALL 0s. Despite the new element not having that value.
}
我一直在寻找解决方案。我似乎找不到任何东西。
我试过的:
- 更改 level_data 的位置,因此它并不总是每次都重新初始化。
- 删除 level_data 而是向 level_collection 添加一个新元素并将 std::get 中返回的值直接复制到向量中
- 通过调试器检查并输出 level_data 确实返回了具有正确值的正确数组。然而,当它被添加到 level_collection 时,它变成了 0。(如果我尝试上面提到的其他东西也没关系)
我敢肯定这里有一个简单的解决方案。我可能只是忽略了一些东西。
编辑:很遗憾,我不能在这个作业中使用 std::array 。我们被告知要利用可用的资源。传递给的函数 level_collection 是“const int *”
解决方案
当你push_back
指向一个向量的指针时,你实际上并没有保留这个指针指向的内存。因此,这在这里不起作用。
相反,您应该使用拥有该int
数组的对象的向量,例如 another std::vector
。您只需更改两行:
std::vector< std::vector<int> > level_collection; // CHANGED
for( auto & i : levels )
{
auto size = std::get< 1 >(i).size();
std::vector<int> level_data{size}; // CHANGED
for( size_t x = 0; x < size; x ++ )
{
level_data[x] = std::get< 1 >(i)[x];
}
for( auto x : level_data)
{
std::cout << x << std::endl; // This works. All the values print correctly. So it did store the information as it should.
}
level_collection.push_back( level_data );
}
for( auto & i : level_collection)
{
std::cout << i[1] << std::endl; // This prints ALL 0s. Despite the new element not having that value.
}
请注意,这是假设您实际上想要一个二维向量。如果你不这样做,你可以直接将push_back
你int
的 slevel_collection
定义为 a std::vector<int>
。
推荐阅读
- c# - 正则表达式 - 忽略空格
- quarkus - AWS Secrets Manager:驱动程序不支持提供的 URL:jdbc-secretsmanager:postgresql
- wordpress - 如何在 WordPress 中通过 user_pass 向用户显示解密的密码?
- python - 异步 SQLAlchemy 示例中的“元”
- php - 为什么我不能在这个特性中使用我的实例?
- c# - 如何使用绝对布局的框架在网格顶部创建弹出窗口?
- opencv - OpenCV 4.5 对应 OpenCV 2.4 cvCreateImageHeader 方法
- protocol-buffers - 使用 grpc-gateway 返回一个 json 映射值
- groovy - 如何使用命名参数并防止使用默认构造函数?
- java - 创建新文件时触发android