boop_bop_scoop
boop_bop_scoop

Reputation: 31

Integer Array to Vector

I'm trying to add an int array into a vector. No matter what I do, the debugger indicates the new vector element is simply "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.
 }

I've been looking hours for a solution. I can't seem to find any.

What I've tried:

I'm sure there's an easy solution here. I might just be overlooking something.

Edit: I unfortunately cannot use std::array in this assignment. We were told to work off of what's available. The function level_collection gets passed to is a "const int *"

Upvotes: 2

Views: 143

Answers (1)

user3684240
user3684240

Reputation: 1580

When you push_back a pointer to a vector, you do not actually preserve the memory that this pointer points to. Therefore, this does not work here.

Instead, you should use a vector of an object which owns the int array, such as another std::vector. You only have to change two lines:

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.
 }

Note that that's assuming you actually want a two-dimensional vector. If you don't, you can just push_back your ints directly to level_collection which should then be defined as a std::vector<int>.

Upvotes: 1

Related Questions