Here is my code:
std::vector<int*> osd;
osd.push_back(new int(2));
osd.push_back(new int(3));
std::ostream_iterator<int*, char> out_iter2(std::cout, " " );
copy(osd.begin(),osd.end(), out_iter2);
output: 0x8e6388 0x8e6a8
How do I make the iterator to print the actual values? Do I need to specialize it?
I made a specialized operator for it but it still doesn't work
std::ostream& operator<<(std::ostream& os, const std::vector<int*>::iterator pd)
{
return os << *pd << std::endl;
}
You can use std::transform with a lambda expression, which gets the actual value from the pointer, such as:
std::ostream_iterator<int, char> out_iter2(std::cout, " " );
std::transform(osd.begin(),
osd.end(),
out_iter2,
[] (int* x) { return *x; }
);
DEMO
EDIT
Here's a possible implementation image from the above link:
template<class InputIt, class OutputIt, class UnaryOperation>
OutputIt transform(InputIt first1, InputIt last1, OutputIt d_first,
UnaryOperation unary_op)
{
while (first1 != last1) {
*d_first++ = unary_op(*first1++);
}
return d_first;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With