Last active
October 30, 2021 10:23
-
-
Save Gnomorian/c8f74594221ab865fbe982d652289313 to your computer and use it in GitHub Desktop.
Using C++17 fold expressions iterate an infinate number of vectors at the same time until the length of the shortest vector
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <vector> | |
#include <iostream> | |
#include <algorithm> | |
constexpr auto iterateVectors = [](auto...vectors) | |
{ | |
constexpr auto getSmallestVector = [](auto...vectors) | |
{ | |
size_t end{ reinterpret_cast<size_t>(std::numeric_limits<size_t>::max) }; | |
((end = std::min(vectors.size(), end)), ...); | |
return end; | |
}; | |
constexpr auto writeRow = [](size_t position, auto...vectors) -> void | |
{ | |
const auto rowLength{ sizeof...(vectors) }; | |
size_t i{ 0 }; | |
((std::cerr << vectors[position] << (++i < rowLength ? ':' : '\n')), ...); | |
}; | |
const size_t iterateFor{ getSmallestVector(vectors...) }; | |
for (size_t i{ 0 }; i < iterateFor; i++) | |
writeRow(i, vectors...); | |
}; | |
int main() | |
{ | |
std::vector<int> A{1, 2, 3, 5}; | |
std::vector<char> B{'a', 'b', 'c'}; | |
std::vector<int> C{5, 6, 7, 8, 9, 10}; | |
iterateVectors(A, B, C); | |
/* | |
Writes: | |
1:a:5 | |
2:b:6 | |
3:c:7 | |
*/ | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment