Skip to content

added vector-print-utility #143

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Jan 3, 2025
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions snippets/cpp/basics/vector-print-utility.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
---
title: std::vector Print Utility
description: Overloads the << operator to print the contents of a vector just like in python.
author: Mohamed-faaris
tags: cpp,printing,debuging,vector,utility
---

```cpp
#include <iostream>
#include <vector>

template <typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& vec) {
os << "[";
for (size_t i = 0; i < vec.size(); ++i) {
os << vec[i]; // Print each vector element
if (i != vec.size() - 1) {
os << ", "; // Add separator
}
}
os << "]";
return os; // Return the stream
}

//std::vector<int> numbers = {1, 2, 3, 4, 5};
//std::cout << numbers << std::endl; // Outputs: [1, 2, 3, 4, 5]

```