Home computickets Two-dimensional vector unknown size and arbitrary access to its elements

Two-dimensional vector unknown size and arbitrary access to its elements

Author

Date

Category

There is a specific section of the code that creates a two-dimensional field M [X] [Y] and scores it with zeros:

std :: vector & lt; std :: vector & lt; int & gt; & gt; vector_map;
vector_map.push_back (std :: vector & lt; int & gt; ());
Vector_map.Resize (Count_H);
For (unsigned int y = 0; y & lt; Count_h; y ++)
{
  For (unsigned int x = 0; X & LT; Count_W; X ++)
  {
    vector_map [x] .push_back (0);
  }
}

Count_W and Count_H initialization occurs at the moment of calling the function in which this code is contained. And …

  1. how to bring it all this thing? It is desirable to implement this using the same two cycles, as above.
  2. How to access an arbitrary field of the resulting matrix and, if necessary, change it?

I was able to make a clogging with values, as well as their conclusion:

std :: vector & lt; int & gt; vector_map;
Vector_map.Resize (Count_h * count_w);
For (unsigned int y = 0; y & lt; Count_h; y ++)
{
  vector_map.push_back (y);
  For (unsigned int x = 0; X & LT; Count_W; X ++)
  {
    vector_map.push_back (x);
  }
}
For (unsigned int y = 0; y & lt; Count_h; y ++)
{
  For (unsigned int x = 0; X & LT; Count_W; X ++)
  {
    STD :: COUT & LT; & LT; vector_map [x * y];
  }
   STD :: COUT & LT; & LT; STD :: ENDL;
}

The result was approximately the following:

0000000000
0000000000.
0000000000.
0000000000.
0000000000.
0000000000.
0000000000.
0000000000.
0000000000.
0000000000.

But how to access and change any arbitrary element – I can’t imagine. I hope for your help.

Thank you in advance.


Answer 1, Authority 100%

Actually, everything turned out to be much easier.
Interface:

std :: vector & lt; std :: vector & lt; int & gt; & gt; vct_map;

Implementation in Functions:

vector & lt; vector & lt; int & gt; & gt; Map (Count_W, Vector & LT; Int & GT; (Count_h)) ;;
vct_map.Resize (Count_W * Count_h);
For (int y = 0; y & lt; Count_h; y ++)
{
  For (int x = 0; X & LT; Count_W; X ++)
  {
      Map [x] [y] = 1;
  }
}
vct_map = map;

The size of the local vector in the functions are set in advance unknown values ​​transmitted through the call to the function, processed, as I need and further is simply assigned to a class member.
It may not be an ideal solution, but very short and understandable. It completely solves my task with access to arbitrary data and reading from the result.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions