The cout is a very easy but powerful techique to debug (for example, submiting code to Online Judge). However, by default, the C++ cout does not accept the vector or list. But we can easily override the << operator:
1 2 3 4 5 6 | template <typename T> ostream& operator <<(ostream& out, const vector<T>& a) { out << "["; bool first = true; for (auto& v : a) { out << (first ? "" : ", "); out << v; first = 0;} out << "]"; return out; } |
template <typename T> ostream& operator <<(ostream& out, const vector<T>& a) { out << "["; bool first = true; for (auto& v : a) { out << (first ? "" : ", "); out << v; first = 0;} out << "]"; return out; }
The above template operator override supports generic type T and you can change the vector to some other container type, such as list, set or even map.
With the above, you then can do this:
1 2 | vector<int> data({1, 2, 3}); cout << data << endl; // this prints [1, 2, 3] |
vector<int> data({1, 2, 3}); cout << data << endl; // this prints [1, 2, 3]
–EOF (The Ultimate Computing & Technology Blog) —
GD Star Rating
loading...
198 wordsloading...
Last Post: Design a Rate Limiter in Python
Next Post: A Concise Python Function to Check Subsequence using Iterator