Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should my function return a pointer to std::vector, or a reference to std::vector?

Tags:

c++

stl

stdvector

I have a std::map<int, std::vector<SomeStruct>>,
and provide a query like std::vector<SomeStruct> FindData(int key).

To prevent copying the whole data, I modify it to be std::vector<SomeStruct>& FindData(int key).
But, there will be no data for certain key, so sometimes I have nothing to return.
In that case, I declare a file scope variable that is an empty std::vector<SomeStruct> and return it.

But if I choose the pointer to vector, that is std::vector<SomeStruct>* FindData(int key) then I can just return NULL for non-existing key.

Which one is better?
I learned that pointer to std::vector is bad(or weird? not sure) in the question (Is there other syntax for this pointer operation?)
And I personally like reference to std::vector too, so that I can use operator[] easier, but the drawback is I have to declare an additional empty variable for it.

Code example are like: In SomeClass.h

typedef std::vector<SomeStruct> DataVec;
typedef std::map<int, DataVec> DataMap;
DataMap m_DataMap;

Now In SomeClass.cpp:

Case 1:

namespace
{
    DataVec EmptyVector;
}

DataVec& FindDatas(int key)
{
    DataMap::iterator It = m_DataMap.find(key);

    if (It == m_DataMap.end()) return EmptyVec;

    return It->second;
}

Case 2:

DataVec* FindDatas(int key)
{
    DataMap::iterator It = m_DataMap.find(key);

    if (It == m_DataMap.end()) return NULL;

    return &(It->second);
}

Reference:
Pros: looks like normal std::vector.
Cons: Additional variable declared.

Pointer:
Pros: Shorter query function and no need other variable.
Cons: looks weird(?!), and you can't juse p[i], you have to (*p)[i], which is annoying.

Which one is better?

like image 270
Marson Mao Avatar asked Mar 30 '13 03:03

Marson Mao


1 Answers

You can also give the reference of output as a parameter, so that you can add some enumerator or bool result as a method output:

    namespace
    {
        DataVec EmptyVector;
    }

    bool FindDatas(int key, DataVec& output)
    {
        DataMap::iterator It = m_DataMap.find(key);

        if (It == m_DataMap.end()) return false;

        output = It->second;
                    return true;
    }
like image 166
fatihk Avatar answered Nov 07 '22 20:11

fatihk