Answer the question
In order to leave comments, you need to log in
How to beautifully output vector elements to the console / just to the stream in C++?
A banal task, implemented a million times, but always, in my opinion, somehow not very beautiful.
There is a container, a couple of iterators, just an array, or something else like that.
It is necessary to display the values somewhere through the separator, so that it is only between the values.
There are all sorts of options - with a check on whether this is the first element, or the last element. I even saw such an exotic one, with the slaughter of the last comma:
template <typename container>
void print(const container& c)
{
std::cout << "(";
std::copy(begin(c), end(c), std::ostream_iterator<container::value_type>(std::cout, ", "));
std::cout << "\b\b)" << std::endl;
}
if (c.size() > 0 ) std::cout << c[0];
for (auto i = begin(c) + 1; i != end(c); ++i) std::cout << ", " << *i;
Answer the question
In order to leave comments, you need to log in
Delimited iterators (Rev. 4)
https://ideone.com/SzWOgx
proof: https://en.cppreference.com/w/cpp/experimental/ost...
template <typename container>
void print(const container& c)
{
auto it = begin(c);
while(it != end(c) && cout << *it++, it != end(c)) { cout << ", "; }
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question