I have std::map<int, std::vector<SomeStruct>> ,
and provide a query like std::vector<SomeStruct> FindData(int key) .
To prevent all data from being copied, I modify it as std::vector<SomeStruct>& FindData(int key) .
But for certain key data will not be, so sometimes I have nothing to return.
In this case, I declare a file scope variable, which is an empty std::vector<SomeStruct> and returns it.
But if I select a pointer to a vector, i.e. std::vector<SomeStruct>* FindData(int key) , then I can just return NULL for a nonexistent key .
Which one is better?
I found out that a pointer to std::vector bad (or weird? Not sure) in the question ( Is there any other syntax for this pointer operation? )
And I personally like the link to std::vector too, so I can use operator[] easier, but the disadvantage is that I have to declare an additional empty variable for it.
Code example: 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 a regular std::vector .
Cons: an additional variable is declared.
Pointer:
Pros: a shorter query function and no other variable.
Cons: it looks weird (?!) And you cannot juse p[i] , you need (*p)[i] , which is annoying.
Which one is better?