Skip to content

Commit 4e4f630

Browse files
Merge pull request technoph1le#143 from Mohamed-faaris/main
added vector-print-utility
2 parents 12f893e + dbf6add commit 4e4f630

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

snippets/cpp/debuging/vector-print.md

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
---
2+
title: Vector Print
3+
description: Overloads the << operator to print the contents of a vector just like in python.
4+
author: Mohamed-faaris
5+
tags: printing,debuging,vector
6+
---
7+
8+
```cpp
9+
#include <iostream>
10+
#include <vector>
11+
12+
template <typename T>
13+
std::ostream& operator<<(std::ostream& os, const std::vector<T>& vec) {
14+
os << "[";
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
19+
}
20+
}
21+
os << "]";
22+
return os; // Return the stream
23+
}
24+
25+
// Usage:
26+
std::vector<int> numbers = {1, 2, 3, 4, 5};
27+
std::cout << numbers << std::endl; // Outputs: [1, 2, 3, 4, 5]
28+
29+
```

0 commit comments

Comments
 (0)