Skip to content

Instantly share code, notes, and snippets.

@airglow923
Created October 30, 2021 19:20
Show Gist options
  • Save airglow923/a5a5d8f07ff79cdbca69426cffa29189 to your computer and use it in GitHub Desktop.
Save airglow923/a5a5d8f07ff79cdbca69426cffa29189 to your computer and use it in GitHub Desktop.
Print range in C++
#include <iostream> // cout
#include <ranges> // range, subrange, cbegin, cend
#include <vector>
namespace {
auto print_range(const std::ranges::range auto &range, bool newline = true)
-> void;
namespace detail {
auto
print(const std::ranges::range auto &value) -> void {
print_range(value, false);
}
auto
print(const auto &value) -> void {
std::cout << value;
}
} // namespace detail
auto
print_range(const std::ranges::range auto &range, bool newline) -> void {
const auto begin = std::ranges::cbegin(range);
const auto end = std::ranges::cend(range);
std::cout << '[';
for (auto &&i : std::ranges::subrange(begin, end - 1)) {
// std::cout << i << ",";
detail::print(i);
std::cout << ',';
}
// std::cout << *(end - 1) << ']';
detail::print(*(end - 1));
std::cout << ']';
if (newline)
std::cout << '\n';
}
} // namespace
auto
main() -> int {
std::vector<std::vector<int>> v{{1, 2, 3}, {2, 4, 6}, {3, 6, 9}};
// [[1,2,3],[2,4,6],[3,6,9]]
print_range(v);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment