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
Asked
Active
Viewed 1.0k times
2
-
2`std::copy` is your friend. – Ulrich Eckhardt Sep 25 '15 at 15:17
-
Seems relevant: http://stackoverflow.com/q/4850473/2069064 – Barry Sep 25 '15 at 15:21
-
@UlrichEckhardt God no. – Barry Sep 25 '15 at 15:24
-
2`std::copy(v.begin(), v.end(), std::ostream_iterator
(std::cout, " "));` – Jonathan H Sep 25 '15 at 15:25
2 Answers
5
You can either define a utility function like
template <typename T>
ostream& operator<<(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;
}
![](../../users/profiles/2296458.webp)
Cory Kramer
- 98,167
- 13
- 130
- 181
2
Yes, it is possible - if you define operator<< for your vector. Something like this:
template <class T>
std::ostream& operator<<(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;
}
![](../../users/profiles/5245033.webp)
SergeyA
- 56,524
- 5
- 61
- 116