H'H
H'H

Reputation: 1680

print member of struct of a vector

I try to print only a struct member from vector of my struct (struct pnt). let me be clear by showing this:

struct pnt {
  char _name;
  int _type;
  bool _aux;
  };

boost::copy(pntVec.begin(),pntVec.end()|
boost::adaptors::transformed(bind(&pnt::_type, _1)), 
std::ostream_iterator<int>(std::cout, "\n"));

but I get an error. I will appreciate if you could please help me to find the reason for that.

Error:

 error: no type named ‘type’ in ‘boost::mpl::eval_if_c<true, boost::range_const_iterator<__gnu_cxx::__normal_iterator<int*, std::vector<int> >, void>, boost::range_mutable_iterator<const __gnu_cxx::__normal_iterator<int*, std::vector<int> >, void> >::f_ {aka struct boost::range_const_iterator<__gnu_cxx::__normal_iterator<int*, std::vector<int> >, void>}’

NOTE: I can olny use C++98, boost v.1.56

Upvotes: 2

Views: 130

Answers (2)

Piotr Skotnicki
Piotr Skotnicki

Reputation: 48467

Boost Adaptor adapts ranges, not single iterators. Similarily, the boost::copy algorithm expects two arguments, where the first one is a range, and the second an output iterator. Having said that, the correct syntax for extracting a single data member from a range, and copying it to an output iterator is:

boost::copy(pntVec | boost::adaptors::transformed(bind(&pnt::_type, _1))
          , std::ostream_iterator<int>(std::cout, "\n"));

Upvotes: 3

sehe
sehe

Reputation: 393134

Alternatively, since Phoenix in a way supersedes Boost Bind + Boost Lambda, you could use Boost Phoenix:

boost::for_each(pntVec, std::cout << bind(&pnt::_type, arg1) << "\n");

or even without bind, if you don't fear a bit of arcane syntax:

boost::for_each(v, std::cout << (arg1->*&pnt::_type) << "\n");

That's pretty expressive. See it Live On Coliru


Also, note that there's mem_fn in Boost/c++11: pntVec | transformed(mem_fn(&pnt::_type))

Upvotes: 3

Related Questions