Last active
August 13, 2021 10:27
-
-
Save RashidLadj/acc4cc44823ed7143f6d9317b945edbf to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <vector> | |
using namespace std; | |
/** Method 1 - Using friend operator in struct or class with public attributes **/ | |
struct vec2D_1 { | |
public: vector<vector<int>> v; | |
vec2D_1(vector<vector<int>> v_){ | |
v = v_; | |
} | |
friend std::ostream& operator<<(std::ostream& os, const vec2D_1& vec) { | |
os << "["; | |
for (int i = 0; i < vec.v.size(); ++i) { | |
os << "["; | |
for (int j = 0; j < vec.v[i].size(); ++j) { | |
os << vec.v[i][j]; | |
if (j != vec.v[i].size() - 1) | |
os << ", "; | |
} | |
if (i != vec.v.size() - 1) | |
os << "],\n"; | |
} | |
os << "]]\n"; | |
return os; | |
} | |
}; | |
/** Method 2 - Using operator (out) in struct or class with public attributes **/ | |
struct vec2D_2 { | |
public: vector<vector<int>> v; | |
vec2D_2(vector<vector<int>> v_){ | |
v = v_; | |
} | |
}; | |
std::ostream& operator<<(std::ostream& os, const vec2D_2& vec) { | |
os << "["; | |
for (int i = 0; i < vec.v.size(); ++i) { | |
os << "["; | |
for (int j = 0; j < vec.v[i].size(); ++j) { | |
os << vec.v[i][j]; | |
if (j != vec.v[i].size() - 1) | |
os << ", "; | |
} | |
if (i != vec.v.size() - 1) | |
os << "],\n"; | |
} | |
os << "]]\n"; | |
return os; | |
} | |
/** Method 3 - Using operator directly with type **/ | |
// Override operator<< for my data structure **/ | |
using Y = vector<vector<int>>; | |
std::ostream& operator<<(std::ostream& os, const Y& vec) { | |
os << "["; | |
for (int i = 0; i < vec.size(); ++i) { | |
os << "["; | |
for (int j = 0; j < vec[i].size(); ++j) { | |
os << vec[i][j]; | |
if (j != vec[i].size() - 1) | |
os << ", "; | |
} | |
if (i != vec.size() - 1) | |
os << "],\n"; | |
} | |
os << "]]\n"; | |
return os; | |
} | |
int main(){ | |
cout << vec2D_1({{0,5,5},{0,5,5}}) << endl; | |
cout << vec2D_2({{0,5,5},{0,5,5}}) << endl; | |
cout << vector<vector<int>>({{0,5,5},{0,5,5}}) << endl; | |
cout << Y({{0,5,5},{0,5,5}}) << endl; | |
} | |
/*** Excution ***/ | |
/** Excution | |
* using MSVS compiler: "cl /EHsc ostream.cpp & ostream.exe" | |
* using gcc or mingw compiler: "g++ -o ostream ostream.cpp & ostream.exe" | |
* using clang compiler: "clang++ -o ostream ostream.cpp; ./ostream" | |
**/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment