Untitled

mail@pastecode.io avatar
unknown
c_cpp
24 days ago
1.7 kB
3
Indexable
Never
	template<typename... Container>
	auto zip(Container&... containers) noexcept 
	{
		// perform a decay type on iterators
		using tuple_type			= std::tuple<std::decay_t<decltype(*std::begin(containers))>...>;
		std::size_t container_size	= std::min({ std::size(containers)... });

		// create a vector for the result
		std::vector<tuple_type> result;
		result.reserve(container_size);

		// create a tuple of iterators
		auto iterators				= std::make_tuple(std::begin(containers)...);
		for (std::size_t i = 0; i < container_size; ++i) 
		{
			std::apply([&result](auto&... it) {	result.emplace_back(*it++...); }, iterators);
		}

		return result;
	}

	template<typename... Ts, typename... Containers>
	void unzip(const std::vector<std::tuple<Ts...>>& zipped, Containers&... containers) {
		// Reserve space in the containers
		((containers.reserve(zipped.size())), ...);

		// Unzip the elements into the containers
		for (const auto& tuple : zipped) 
		{
			std::apply([&](auto&&... args) 
				{
					((containers.push_back(args)), ...);
				}, 
				tuple);
		}
	}

	// ###################################################################################################################

	template<uint _On, typename... Ts>
	void sort(std::vector<std::tuple<Ts...>>& zipped,
			  std::function<bool(typename std::remove_reference_t<typename std::tuple_element<_On, std::tuple<Ts...>>>::type,
								 typename std::remove_reference_t<typename std::tuple_element<_On, std::tuple<Ts...>>>::type)> f)
	{
		std::sort(zipped.begin(), zipped.end(),
			[&](const auto& a, const auto& b)
			{
				return std::get<_On>(a) < std::get<_On>(b);
				//return f(std::get<_On>(a), std::get<_On>(b));
			});
	}
Leave a Comment