I have the following function:
std::list<std::shared_ptr<Object>> AnimalManager::GetObjectsOfType(std::string type)
{
std::pair <std::multimap<std::string, std::shared_ptr<Object>>::iterator, std::multimap<std::string, std::shared_ptr<Object>>::iterator> ret;
ret = m_objects.equal_range(type);
std::list<std::shared_ptr<Object>> objectsOfType(ret.first, ret.second);
return objectsOfType;
}
I'm creating a list with a range of iterators but I'm getting an error. I due to the iterators in the multimap are pairs and elements in list are uniques. But I don't want to iterate thought iterators because I'll lose the benefit I get using std::multimap
instead other data strcuture with O(1) insertion but O(n) find.
Is possible to create a list as I want to do it? Or would it be better If I use another design pattern or data structure?
What you need it std::transform
to transform the range into a different one. Making use of a lambda you could construct the list like
std::list<std::shared_ptr<Object>> AnimalManager::GetObjectsOfType(std::string type)
{
auto ret = m_objects.equal_range(type);
std::list<std::shared_ptr<Object>> objectsOfType;
std::transform((ret.first, ret.second, std::back_inserter(objectsOfType),
[](const auto& pair){ return pair.second; });
return objectsOfType;
}