How to generate a list of unknown number of items without using a loop

Is it possible to generate a list of items if I don't know how many there are in the list, without using a loop?

Here's an example (using a loop):

vector<int> bits(int N) {
    vector<int> v;

    while (N != 0) {
        v.push_back(N & 1);
        N >>= 1;
    }

    return v;
}

In this example, I don't know how many items the returned vector will have beforehand. And while it is totally fine using a loop to implement this function, my question (as I'm trying to learn C++ and STL) is if there's a way to do the same thing but without any loops.


Solution 1:

Something along these lines perhaps, if you absolutely insist on going out of your way to get STL to run loops for you:

class BitIterator {
 public:
  using value_type = int;
  using difference_type = std::size_t;
  using pointer = int*;
  using reference = int&;
  using iterator_category = std::input_iterator_tag;

  BitIterator(int n = 0) : n_(n) {}

  int operator*() const { return n_ & 1; }
  BitIterator& operator++() { n_ >>= 1; return *this; }

  bool operator==(const BitIterator& other) const { return n_ == other.n_; }
  bool operator!=(const BitIterator& other) const { return n_ != other.n_; }

 private:
  int n_ = 0;
};

std::vector<int> bits(int N) {
    return {BitIterator(N), BitIterator(0)};
}

Demo