Created
April 3, 2020 15:53
-
-
Save haruo-wakakusa/d29558f064b0a2698f965eb54dcd096f to your computer and use it in GitHub Desktop.
python2 range in C++
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> | |
template<class T> class vector; | |
template<class T> std::ostream& operator<<(std::ostream&, const vector<T>&); | |
template<class T> class vector : virtual public std::vector<T> { | |
public: | |
friend std::ostream& operator<< <T> (std::ostream &out, const vector<T> &v); | |
}; | |
template<class T> | |
std::ostream& operator<< (std::ostream &out, const vector<T> &v) { | |
if (v.size() == 0) { | |
out << "[]"; | |
} else if (v.size() == 1) { | |
out << "[" << v.front() << "]"; | |
} else { | |
out << "[" << v.front(); | |
for (auto i = v.begin() + 1; i != v.end(); ++i) | |
out << ", " << *i; | |
out << "]"; | |
} | |
return out; | |
} | |
vector<int> range(int start, int end, int step) { | |
vector<int> v; | |
if (step > 0) { | |
for (int i = start; i < end; i += step) v.push_back(i); | |
} | |
if (step < 0) { | |
for (int i = start; i > end; i += step) v.push_back(i); | |
} | |
return v; | |
} | |
vector<int> range(int start, int end) { return range(start, end, 1); } | |
vector<int> range(int end) { return range(0, end, 1); } | |
int main() { | |
std::cout << "range(5, 10) = " << range(5, 10) << std::endl; | |
std::cout << "range(0, 10, 3) = " << range(0, 10, 3) << std::endl; | |
std::cout << "range(-10, -100, -30) = " << range(-10, -100, -30) << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment