Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ostream_iterator on vector of pointers

Tags:

c++

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; 
}
like image 729
Carlos Miguel Colanta Avatar asked Nov 19 '25 22:11

Carlos Miguel Colanta


1 Answers

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;
}
like image 104
songyuanyao Avatar answered Nov 22 '25 13:11

songyuanyao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!