Reputation: 1921
I have written below code to convert keys in map
or multimap
to set
:
template<typename STLContainer>
inline auto CopyContanerKeyToSet(const STLContainer& cont)
{
std::set<decltype(cont.begin()->first)> lset;
std::transform(cont.begin(),cont.end(),std::inserter(lset,lset.end()),[](const auto it) { return it.first;});
return lset
}
Now there is requirement that sometimes I need to convert keys into vector
as well. So I just want to know how to write template function that can accept vector
or set
as template argument and after that create that container accordingly.
Upvotes: 1
Views: 309
Reputation: 180415
We can solve this with a Template template parameter. This allows us to specify just the main type without specifying the template type of that type. Doing that gives us
template< template<typename ...> class OutputContainer, typename STLContainer>
inline auto CopyContanerKeyToSet(const STLContainer& cont)
{
OutputContainer<typename STLContainer::key_type> lset;
std::transform(cont.begin(),cont.end(),std::inserter(lset,lset.end()),[](const auto it) { return it.first;});
return lset;
}
And then we can use that with something like this
int main()
{
std::map<std::string, int> foo{ {"this", 1}, {"second", 1} };
auto output = CopyContanerKeyToSet<std::vector>(foo);
for (const auto& e : output)
std::cout << e << " ";
}
Which gives us
second this
I also changed <decltype(cont.begin()->first)>
to <typename STLContainer::key_type>
as value_type
of the map
/multimap
has a const key_type
for the std::pair
which we do not want for the vector
/set
.
Upvotes: 2