Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending array into vector

Tags:

c++

c++11

vector

I think it is a trivial question, but I couldn't find a specific solution to it. I'm trying to append array into a vector, using push_back() function. Here is the code:

int main()
{
  std::vector<int*> matchVector;

  int msmTemp[3];

  msmTemp[0] = 1;
  msmTemp[1] = 2;
  msmTemp[2] = 3;
  matchVector.push_back(msmTemp);
  msmTemp[0] = 4;
  msmTemp[1] = 7;
  msmTemp[2] = 0;
  matchVector.push_back(msmTemp);

  for(auto i : matchVector)
  {
    for(int j = 0; j<3; j++)
    {
      cout<<i[j]<<", ";
    }
    cout<<"\n";
  }

  return 0;
}

The output I'm getting is 4,7,0 two times. I don't understand as to why I'm not able to see the previous values, namely 1,2,3? Is it because of the type of vector matchVector defined above? I think it needs to be array only.

like image 452
archity Avatar asked Dec 18 '22 22:12

archity


1 Answers

A int* is a pointer to an integer.

An int[3] is an array of 3 integers.

An array of 3 integers "decays" at the drop of a hat to a pointer to the first element.

When you do push_back(msmTemp), you push a pointer to the first element of msmTemp into the vector.

Pointers in C++ do not own what they point to. The vector afte the two push_backs contains two pointers, both to the same array msmTemp.

When you later iterate over the vector, you get two pointers in turn. Each points to msmTemp.

You then use [] to index those pointers. When you have a pointer to the first element of an array, you can use [] to access the other elements of the array. [0] is the first element, [1] the second, etc.

So you look at the 3 elements in msmTemp (luckily it has 3) and look at them twice, because you have two pointers into it in the vector.

You can inject elements like this:

std::vector<int> matchVector;
int msmTemp[3];
msmTemp[0]={1};
msmTemp[1]={2};
msmTemp[2]={3};
matchVector.insert( matchVector.end(), std::begin(msmTemp), std::end(msmTemp) );

etc. This ends up with a vector containing 6 elements, not two arrays.

If you want arrays as values you need std::array:

std::vector< std::array<int,3> > matchVector;
std::array<int, 3> msmTemp;

and then your code works as written. std::array is a library type that acts sort of like a raw array, but it doesn't have the decay-to-pointer problems of a raw array.

like image 104
Yakk - Adam Nevraumont Avatar answered Jan 09 '23 06:01

Yakk - Adam Nevraumont