开发者

Cant send NULL to a function getting vector

I have this function:

    void RegMatrix::MatrixInit(int numRow,int numCol, std::vector<double> fill)

    {

      do something;

    }

and i want to send this:

MatrixInit(numRow,numCol,NULL);

how can i pass NULL as v开发者_Go百科ector?


You cannot pass NULL as vector, you could instead pass an empty vector like this:

MatrixInit( numRow, numCol, std::vector<double>() )

Note that you would be better off taking the fill vector as const&.


In order to pass NULL, you need to change your parameter to accept a vector* pointer instead, eg:

void RegMatrix::MatrixInit(int numRow, int numCol, std::vector<double> *fill)
{
    if (fill != NULL)
    {
        do something with fill;
    }
}

When you need to pass in a vector, you would then do it like this:

std::vector<double> v;
MatrixInit(numRow, numCol, &v); 


If you want a value that represents a special case, you can make a static variable and test against it.

static std::vector<double> null_fill;

void RegMatrix::MatrixInit(int numRow,int numCol, const std::vector<double> & fill = null_fill)
{
    if (&fill == &null_fill)
        // do something special
    else
        // do something;
} 


You could make the argument type boost::optional<std::vector<double> >

As the name says, that's an optional argument. If you don't use the argument, you pass boost::none instead. (not NULL; that's a null pointer constant and we're not using pointers here).


You cannot have a null vector in C++.

C++ is a value-type language.A variable of type vector contains the value of vector directly, NOT a reference to a vector like in java.

MatrixInit(numRow,numCol,NULL);

The above statement will give you an error : Cannot convert NULL(zero) to std::vector.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜