Last active
January 5, 2016 02:45
-
-
Save TerrorJack/e1c81fab63eac791fa1b to your computer and use it in GitHub Desktop.
Simple lazy vector in C++ which enables parallel evaluation.
This file contains hidden or 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 <functional> | |
| #include <vector> | |
| template<typename T> using VectorIndex = typename std::vector<T>::size_type; | |
| template<typename T> | |
| class LazyVector { | |
| public: | |
| LazyVector(); | |
| LazyVector(const T &); | |
| LazyVector(const std::vector<T> &); | |
| std::vector<T> forceSequential(); | |
| private: | |
| VectorIndex<T> _size; | |
| std::function<T(VectorIndex<T>)> _f; | |
| }; | |
| template<typename T> | |
| LazyVector<T>::LazyVector() : _size(0) { } | |
| template<typename T> | |
| LazyVector<T>::LazyVector(const T &elem) : _size(1), _f([=](VectorIndex<T>) { return elem; }) { } | |
| template<typename T> | |
| LazyVector<T>::LazyVector(const std::vector<T> &elems) : _size(elems.size()), | |
| _f([=](VectorIndex<T> i) { return elems[i]; }) { } | |
| template<typename T> | |
| std::vector<T> LazyVector<T>::forceSequential() { | |
| std::vector<T> v; | |
| v.reserve(_size); | |
| for (VectorIndex<T> i = 0; i < _size; ++i) | |
| v.push_back(_f(i)); | |
| return v; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment