在指针向量上使用ostream_iterator

时间:2015-06-04 03:00:12

标签: c++

这是我的代码:

x_values

输出:0x8e6388 0x8e6a8

如何让迭代器打印实际值?我需要专门化吗?

我为它做了一个专门的操作员,但它仍然没有工作

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);

1 个答案:

答案 0 :(得分:4)

您可以将std::transform与lambda表达式一起使用,该表达式从指针获取实际值,例如:

std::ostream_iterator<int, char> out_iter2(std::cout, " " );
std::transform(osd.begin(), 
               osd.end(), 
               out_iter2, 
               [] (int* x) { return *x; }
              );

DEMO

修改

以下是上述链接的可能实施图片:

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;
}