简体   繁体   中英

populate Vector in C++

I am working on populate_vector function in C++ As I am a newbie in C++ language, it is quite difficult to get into vector concept.

  • What I want to do is get x, y for input(which is above but not showing here) and have (3x * 2y) size vectors. And fill the vectors with the random numbers for representing a trio of pixels, (red, green, blue)
  • a 1-dimensional array to represent a 2-dimensional matrix

The question is: The code does not work properly. When I run it, it just shows the input entered code and then when entering the input, then that's it. I dont know why it does not work and how to change it

    vector<int> xVector((3*x) * (2*y));
    vector<int>::iterator iter;
    srand((unsigned)time(NULL));
    //  int a = rand() % 255 +1;


    for (int i = 0; i < xVector.size(); i++)
    {
    int b = rand() % 255 + 1;
    int c = rand() % 255 + 1;

    xVector.push_back(b);
    xVector.push_back(c);
    }

    for (auto i = 0; i < xVector.size(); i++)
    {
      cout << "xVector[" << i << "] : " << xVector[i] << endl;
    }

You iterate the vector, and in each element you add two more. so it is a never ending loop.

the .push_back will add at the end of the vector that element, so size() is always increasing.

I would suggest something like this.

vector<int> xVector((3*x) * (2*y));
std::generate(xVector.begin(), xVector.end(), []{return rand() % 255 + 1;});

or if you want to use a for loop

for (int i = 0; i < xVector.size(); ++i){
     xVector[i] = rand() % 255 + 1;
}

it will set a random number for each element.

I recommend using a vector of struct .
Example:

struct Point
{
  int x;
  int y;
};
std::vector<Point> database;

Maybe you want a 2d container of pixel attributes:

struct Pixel
{
  unsigned int red;
  unsigned int green;
  unsigned int blue;
};
std::vector< std::vector<Pixel> > bitmap;

Using a vector (or array), where odd entries are X and even entries are Y, is just plain messy. Parallel arrays are difficult to maintain and lead to a lot of defects.

The better solutions involve using arrays or vectors of structures.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM