I\'m trying to implement a function similar to std::transform algorithm but instead of taking the output iterator by an argument I want to create and return a c
The following method allows to transform containers of any type from the standard library (there is a problem with std::array, see below). The only requirement for the container is that it should use default std::allocator classes, std::less, std::equal_to and std::hash function objects. So we have 3 groups of containers from the standard library:
Containers with one non-default template type parameter (type of value):
std::vector, std::deque, std::list, std::forward_list, [std::valarray]std::queue, std::priority_queue, std::stackstd::set, std::unordered_setContainers with two non-default template type parameters (type of key and type of value):
std::map, std::multi_map, std::unordered_map, std::unordered_multimapContainer with two non-default parameters: type parameter (type of value) and non-type parameter (size):
std::arrayconvert_container helper class convert types of known input container type (InputContainer) and output value type (OutputType) to the type of the output container(typename convert_container):
template
struct convert_container;
// conversion for the first group of standard containers
template class C, class IT, class OT>
struct convert_container, OT>
{
using type = C;
};
// conversion for the second group of standard containers
template class C, class IK, class IT, class OK, class OT>
struct convert_container, std::pair>
{
using type = C;
};
// conversion for the third group of standard containers
template
<
template class C, std::size_t N, class IT, class OT
>
struct convert_container, OT>
{
using type = C;
};
template
using convert_container_t = typename convert_container::type;
transform_container function implementation:
template
<
class InputContainer,
class Functor,
class InputType = typename InputContainer::value_type,
class OutputType = typename std::result_of::type,
class OutputContainer = convert_container_t
>
OutputContainer transform_container(const InputContainer& ic, Functor f)
{
OutputContainer oc;
std::transform(std::begin(ic), std::end(ic), std::inserter(oc, oc.end()), f);
return oc;
}
See live example with the following conversions:
std::vector -> std::vector ,std::set -> std::set ,std::map -> std::map .std::array conversion doesn't compile because std::array haven't insert method which is needed due to std::inserter). transform_container function shouldn't also work for this reason with the following containers: std::forward_list, std::queue, std::priority_queue, std::stack, [std::valarray].