V
V
Vasily Melnikov2018-12-17 16:28:52
C++ / C#
Vasily Melnikov, 2018-12-17 16:28:52

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;
}

Probably the most acceptable would be
if (c.size() > 0 ) std::cout << c[0];
for (auto i = begin(c) + 1; i != end(c); ++i) std::cout << ", " << *i;

But suddenly someone will tell you something from their experience

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Roman, 2018-12-17
@BacCM

Delimited iterators (Rev. 4)
https://ideone.com/SzWOgx
proof: https://en.cppreference.com/w/cpp/experimental/ost...

A
Alexander Movchan, 2018-12-17
@Alexander1705

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 question

Ask a Question

731 491 924 answers to any question