I am going to store some objects keyed by various numbers. Most numbers will have no objects, some will have 1, and some will have multiple.
std::map<int, std::vector<MyObject>> myObjects;
// or...
std::vector<std::vector<MyObject>> myObjects;
std::vector<MyObject> GetObjectsForNumber( int number )
{
// how best to do this?
if ( -check if there is a vector for the number- )
{
return myObjects[number];
// or...
return myObjects.at(number);
}
else
{
// return empty vector?
}
}
Should I use a map or vector, and how should I implement the function?
What you are looking for is probably the multimap, see http://www.cplusplus.com/reference/stl/multimap/.
But you should point out what exactly your goals are – memory efficiency, performance? Also, how is the “distribution” of the values over the keys? If it’s an important decision, you should prototype.
P.S.: Don’t write
but rather
GCC will interpret >> as operator>> otherwise.