Skip to content

Commit edf11fc

Browse files
added vector-print-utility
1 parent 492a306 commit edf11fc

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
---
2+
title: std::vector Print Utility
3+
description: Overloads the << operator to print the contents of a vector just like in python.
4+
author: Mohamed-faaris
5+
tags: cpp,printing,vector,utility
6+
---
7+
8+
```cpp
9+
#include <iostream> // Includes the input/output stream library
10+
#include <vector> // Includes the vector container
11+
12+
template <typename T>
13+
std::ostream& operator<<(std::ostream& os, const std::vector<T>& vec) {
14+
os << "["; // Begin vector formatting with an opening bracket
15+
for (size_t i = 0; i < vec.size(); ++i) {
16+
os << vec[i]; // Print each vector element
17+
if (i != vec.size() - 1) {
18+
os << ", "; // Add separator between elements except after the last one
19+
}
20+
}
21+
os << "]"; // Close vector formatting with a closing bracket
22+
return os; // Return the stream to enable chaining
23+
}
24+
```

0 commit comments

Comments
 (0)