You will need to do a little work. You need to implement your own iterator class and begin()
and end()
:
struct Permutation { std::vector<std::string> items; std::vector<short> permutationValue; class iterator; iterator begin(); iterator end(); };
Your iterator class will be a random access iterator:
#include <iterator> class Permutation::iterator : public std::iterator<std::random_access_iterator_tag, std::string> { };
It is important to inherit from std::iterator
so that your custom iterator works correctly with <algorithm>
.
There are several possible ways to implement an iterator. But the general idea is that your iterator will save a pointer to its permutation object and the current index position in its private members of the class:
private: Permutation *p; size_t pos;
Its operator*
obvious:
public: std::string &operator*() const { return p->items[p->permutationValue[pos]]; }
You will need to implement all the other iterator operators that increase / decrease the progress of the random access iterator, the operators ++
, --
, +
, -
, +=
, -=
, just adding or subtracting pos
.
You also need to implement all the comparison operators for your iterator class: <
, >
, =
!=
, <=
And >=
, just by comparing pos
.
These bits will be a little tedious, but inevitable.
Now all you have to do is implement begin()
and end()
by creating this instance of the iterator, setting the initial pos
to 0 or items.size();
. Everything is ready. Now you can use range iteration.
For additional credit, you can also implement const_iterator
.
In conclusion: it will be a bit of work, but it is not very difficult.