Home > Net >  C Copy Map to Vector Templated
C Copy Map to Vector Templated

Time:05-04

I have the following:

template<typename MapT>
std::vector<int> mapToVec(const MapT &_map) {
   std::vector<int> values;
   for(const auto &entry : _map)
   {
      values.push_back(entry.second);
   }
   return values;
}

Obviously this only works if the value type of the map is an int. How do I template this further to convert a map to a vector of it's value type?

So essentially it should return a vector of the values (or second elements of the key-value pairs) of any std::map passed in.

CodePudding user response:

You can use typename MapT::mapped_type as the std::vector::value_type, eg:

template<typename MapT>
std::vector<typename MapT::mapped_type> mapToVec(const MapT &_map)
{
   std::vector<typename MapT::mapped_type> values;
   values.reserve(_map.size());
   for(const auto &entry : _map)
   {
      values.push_back(entry.second);
   }
   return values;
}

Online Demo

Alternatively, you can share a template argument for both the std::vector::value_type and the std::map::mapped_type, eg:

template<typename KeyT, typename ValueT>
std::vector<ValueT> mapToVec(const std::map<KeyT, ValueT> &_map)
{
   std::vector<ValueT> values;
   values.reserve(_map.size());
   for(const auto &entry : _map)
   {
      values.push_back(entry.second);
   }
   return values;
}

Online Demo

CodePudding user response:

In C 23, you can combine views::keys with ranges::to

template<typename MapT>
auto mapToVec(const MapT &_map) {
  return _map | std::views::values | std::ranges::to<std::vector>();
}

Demo

  •  Tags:  
  • c
  • Related