returning iterators to boost adaptor-transformed container

Viewed 608

I would like to offer to users of a class the possibility to iterate over a member container, but with a transform applied to the elements. Boost adaptors seem to be a good fit for transforming a container, but I do not know how could I possibly apply it to my use case.

The function returns an IterPair template wrapping the begin and end iterators and it works without the transform. However, with the transform I am returning a pair of iterators of a local variable. Making the transformed container a member is not possible since it does not have a default constructor.

class A
{
public:
    IterPair get_elems()
    {
          auto tr_vect =  vect_ | boost::adaptors::transformed(std::mem_fn(&std::string::c_str));
          return {std::begin(tr_vect), std::end(tr_vect)};
    }
private:
    std::vector<std::string> vect_;
}
2 Answers
Related