首页 > 解决方案 > 整数数组到向量

问题描述

我正在尝试将一个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.
 }

我一直在寻找解决方案。我似乎找不到任何东西。

我试过的:

我敢肯定这里有一个简单的解决方案。我可能只是忽略了一些东西。

编辑:很遗憾,我不能在这个作业中使用 std::array 。我们被告知要利用可用的资源。传递给的函数 level_collection 是“const int *”

标签: c++arraysvector

解决方案


当你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_backint的 slevel_collection定义为 a std::vector<int>


推荐阅读