Created
November 17, 2023 08:03
-
-
Save matthewelmer/9c90f450f3a226c3633c866ffd7819e9 to your computer and use it in GitHub Desktop.
`operator<<` overload for `std::array` and `std::vector`
This file contains hidden or 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
#pragma once | |
#include <array> | |
#include <cmath> | |
#include <vector> | |
#include <iomanip> | |
#include <ostream> | |
using std::ostream; | |
using std::ios_base; | |
using std::round; | |
using std::setw; | |
using std::scientific; | |
using std::setprecision; | |
template <size_t N> | |
ostream& operator<<(ostream& out, std::array<double, N> arr) { | |
ios_base::fmtflags original_flags{out.flags()}; | |
out << scientific << setprecision(4); | |
out << "[" << setw(11) << arr[0]; | |
for (size_t i{1}; i < N; i++) { | |
out << ", "; | |
out << setw(11) << arr[i]; | |
} | |
out << "]"; | |
out.flags(original_flags); | |
return out; | |
} | |
template <typename T> // Unused but why not | |
ostream& operator<<(ostream& out, std::vector<T> vec) { | |
ios_base::fmtflags original_flags{out.flags()}; | |
out << "[" << vec[0]; | |
for (size_t i{1}; i < vec.size(); i++) { | |
out << ", "; | |
out << vec[i]; | |
} | |
out << "]"; | |
out.flags(original_flags); | |
return out; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment