5

I need to cout a vector. Not just an element of it, but the whole thing. For example std::cout << vectorName; Something like that, hope it makes sense. Any ideas? Thanks in advance

OpenGLmaster1992
  • 281
  • 2
  • 5
  • 13

2 Answers2

8

You can either define a utility function like

template <typename T>
std::ostream& operator<<(std::ostream& output, std::vector<T> const& values)
{
    for (auto const& value : values)
    {
        output << value << std::endl;
    }
    return output;
}

Or iterate yourself

for (auto const& value : values)
{
    std::cout << value << std::endl;
}
happy-san
  • 810
  • 1
  • 7
  • 27
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
4

Yes, it is possible - if you define operator<< for your vector. Something like this:

#include <iterator>

template <class T>
std::ostream& operator<<(std::ostream& out, const std::vector<T>& container) {
   out << "Container dump begins: ";
   std::copy(container.cbegin(), container.cend(), std::ostream_iterator<T>(out, " " ));
   out << "\n";
   return out;
}

happy-san
  • 810
  • 1
  • 7
  • 27
SergeyA
  • 61,605
  • 5
  • 78
  • 137