1

I have vector that contains pointers to string vector<string*> and I want to use ostream_iterator to output strings value. I try to override << operator but it doesn't work: std::ostream &operator<<(std::ostream &os, string* p) { return os << *p; }. It still output variables adreses.

Anton
  • 45
  • 2
  • 4
  • 1
    Where do you put this, and where do you (want to) use it? – BoBTFish Feb 18 '14 at 09:51
  • 4
    Comedy option: `std::transform(begin(vec), end(vec), std::ostream_iterator, [](const std::string* foo){return *foo});` And I hope I got it right. ;-) – Xarn Feb 18 '14 at 09:52
  • 1
    @Xarn it looks like you did, and that's *awesome*. I was about to pound out a `std::for_each` but I like that so much better =P – WhozCraig Feb 18 '14 at 09:53
  • 1
    @WhozCraig I actually didn't, notice missing `(std::cout)` (or other stream) for the `ostream_iterator` and missing semicolon in lambda. I blame lack of coffee. :-) On a more serious note, [a quick test with coliru](http://coliru.stacked-crooked.com/a/bb0fa4c3ea49aba6) shows that specializing `<<` for `std::string*` seems to work properly. – Xarn Feb 18 '14 at 10:06
  • duplicate: http://stackoverflow.com/questions/4447827/why-does-ostream-iterator-not-work-as-expected – Emil Condrea Feb 18 '14 at 10:19

1 Answers1

0

Well, it is not quite clear what you are actually asking, but your specialization of << works for me when tested. That is, this works as expected:

std::ostream &operator<<(std::ostream &os, std::string* p){
    return os << *p;
}


int main(){

    std::string str("Hello World\n");
    std::vector<std::string*> vec{&str};


    for (std::size_t i = 0; i < vec.size(); i++){
        std::cout << vec[i];
    }

output is Hello World.

However, for a bit more fun, you can do a nice, idiomatic oneliner:

std::transform(begin(vec), end(vec), std::ostream_iterator<std::string>(std::cout), [](const std::string* foo){return *foo;});

You can replace std::cout in the example with any output stream you want.

Xarn
  • 3,460
  • 1
  • 21
  • 43