2

I have a class Pixel and a class Image with a function used to update a pixel line. I want to initialize the pixel line. My problem is to initialize the vector. Actually I have this :

bool UpdateLine(std::vector<Pixel>& line, int nb)
{
    bool noError = true;
    line = new std::vector<Pixel>(nb);
    // Do some stuff
    return noError;
}

When I try this I have :

no viable overloaded '='

How can I initialize the vector ?

gsamaras
  • 71,951
  • 46
  • 188
  • 305
A.Pissicat
  • 3,023
  • 4
  • 38
  • 93

2 Answers2

3

The expression you are using:

new std::vector<Pixel>(nb)

returns a pointer to std::vector<Pixel> (i.e.: std::vector<Pixel> *), and not a std::vector<Pixel>, which is what you need.


A distinction between initialization and assignment has to be done: you are assigning to line and not initializing it.

You can create a new vector and assign it to line by means of an assignment operator:

line = std::vector<Pixel>(nb);
JFMR
  • 23,265
  • 4
  • 52
  • 76
1

What you do is assignment, not initialization.

Initializing a vector could be done like this:

std::vector<int> second (4,100); // four ints with value 100

In your case however, the vector is already declared outside of the function, so in that case you use vector::resize and do this:

line.resize(nb); // creates 'nb' objects 'Pixel'

PS: You don't need new keyword, except if you dynamically allocating memory for your vector.

gsamaras
  • 71,951
  • 46
  • 188
  • 305