allo
allo

Reputation: 4236

How to fill a C++ container using a (lambda) function?

I want to initialize a container with pointers to objects. I currently have a loop like this:

for(int i=0;i < n;i++) {
    container.push_back(new Object());
}

Which C++ operation (i.e. similar to std::transform) is the right to replace this loop and initialize a container with n newly created objects?

Upvotes: 19

Views: 14542

Answers (3)

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275585

The goal is this syntax:

std::vector<Object*> v1 = generate([](auto&&){ return new Object; }, 10).make_container();

where we say we want to generate 10 elements with a specific lambda, then we create a container of the asked for type.

It requires some boilerplate. First, an input iterator that counts and calls a function:

template<class F>
struct generator_iterator {
  F f;
  std::size_t i = 0;

  using self=generator_iterator;
  friend bool operator==(self const& lhs, self const& rhs){ return lhs.i==rhs.i; }
  friend bool operator!=(self const& lhs, self const& rhs){ return lhs.i!=rhs.i; }
  using reference=std::result_of_t<F const&(std::size_t const&)>;
  using value_type=std::decay_t<reference>;
  using difference_type=std::ptrdiff_t;
  using pointer=value_type*;
  using iterator_category=std::input_iterator_tag;

  self& operator++(){++i; return *this;}
  self operator++(int){auto tmp=*this; ++*this; return tmp;}
  reference operator*()const{ return f(i); }
  pointer operator->()const { return std::addressof(f(i)); }

  friend difference_type operator-( self const& lhs, self const& rhs ) { return lhs.i-rhs.i; }
  self& operator-=( difference_type rhs )& {
    i-=rhs;
    return *this;
  }
  self& operator+=( difference_type rhs )& {
    i+=rhs;
    return *this;
  }
  friend difference_type operator+( self lhs, difference_type rhs ) {
    lhs += rhs;
    return lhs;
  }
  friend difference_type operator-( self lhs, difference_type rhs ) {
    lhs -= rhs;
    return lhs;
  }

};

Next, a range primitive, with a .make_container() method that lets you convert ranges to containers either by passing the type explicitly or implicitly:

template<class It>
struct range_t {
  It b, e;
  It begin() const { return b; }
  It end() const { return e; }

private:
  struct container_maker {
    range_t const* self;
    template<class C>
    operator C()&& {
      return {self->begin(), self->end()};
    }
  };
public:
  container_maker make_container()const{
    return {this};
  }
  // C is optional
  template<class C>
  C make_container()const{
    return make_container();
  }
};
template<class It>
range_t<It> range( It s, It f ) {
  return {std::move(s), std::move(f)};
}

We then glue these together:

template<class F>
auto generate( F&& f, std::size_t count ) {
  generator_iterator<std::decay_t<F>> e{f, count};
  generator_iterator<std::decay_t<F>> b{std::forward<F>(f)};
  return range( std::move(b), std::move(e) );
}

and this compiles:

std::vector<Object*> v1 = generate([](auto&&){ return new Object; }, 10).make_container();

Live example.

Upvotes: 1

Ron
Ron

Reputation: 15511

Use std::generate:

constexpr int n = 10;
std::vector<Object*> v1(n);
std::generate(v1.begin(), v1.end(), [](){ return new Object(); });

or std::generate_n:

std::vector<Object*> v2;
v2.reserve(n); // pre-allocate sufficient memory to prevent re-allocations
               // (you should have done in original loop approach as well)
std::generate_n(std::back_inserter(v2), n, [] { return new Object(); });

Upvotes: 18

songyuanyao
songyuanyao

Reputation: 172934

You could use std::generate_n and std::back_inserter with lambda.

std::generate_n(std::back_inserter(container), n, [] { return new Object(); });

Upvotes: 7

Related Questions