Skip to content

Instantly share code, notes, and snippets.

@jonwis
Created November 21, 2023 05:01
Show Gist options
  • Save jonwis/e08ecd37f3513565bb8dfa3d1345cf2e to your computer and use it in GitHub Desktop.
Save jonwis/e08ecd37f3513565bb8dfa3d1345cf2e to your computer and use it in GitHub Desktop.
A function that transmutes any container into a vector of another type
#include <vector>
#include <algorithm>
#include <iterator>
#include <functional>
// Given a container that supports "begin(c)" / "end(c)", uses std::transform plus a
// provided transmutor function to produce an output vector of the results. The
// type of the vector returned is derived from the return type of the transmutor
// operation.
template<typename Z, typename Q>
auto transmute(Z const& container, Q&& transmutor) -> std::vector<decltype(std::invoke(transmutor, *std::begin(container)))>
{
std::vector<decltype(std::invoke(std::forward<Q>(transmutor), *std::begin(container)))> results;
std::transform(std::begin(container), std::end(container), std::back_inserter(results), std::forward<Q>(transmutor));
return results;
}
// Example using the transmute function to switch an array of integers into
// a vector of floats
std::vector<float> convert(std::array<int, 4> const& items)
{
return transmute(items, [](int f) { return static_cast<float>(f); });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment