1

This prints the address for my string, but not its' contents,

#include <memory>
#include <string>
#include <list>
#include <iostream>
#include <iterator>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    unique_ptr<list<shared_ptr<string>>> upList (new list<shared_ptr<string>>);
    shared_ptr<string> spNation (new string ("India"));
    upList->push_back (spNation);
    copy (upList->begin(), upList->end(), ostream_iterator<shared_ptr<string>> (cout, "\n "));
    return 0;
}

My questions are:

  1. What ostream_iterator<shared_ptr<string>> is taking shared_ptr or strings as its' prime object.
  2. How to print actual string contents (i.e. India) using this approach.
  3. Is this approach is preferable over traditional for loop to print all node contents.
masT
  • 804
  • 4
  • 14
  • 29

2 Answers2

3

What ostream_iterator<shared_ptr<string>> is taking shared_ptr or strings as its' prime object.

You've instantiated ostream_iterator for shared_ptr<string>, so that is what it will attempt to output.

How to print actual string contents (i.e. India) using this approach.

If you really want to use shared pointers for some reason, then you can't use copy since that won't undo the extra level of indirection. Either use a plain loop, or get rid of the unnecessary indirection:

list<string> list;
list.push_back("India");
copy(list.begin(), list.end(), ostream_iterator<string>(cout, "\n "));

Of course, it doesn't look as exciting without all the arrows, templates, new-expressions and pseudohungarian warts, but anyone trying to maintain the code won't thank you for adding such embellishments.

Is this approach is preferable over traditional for loop to print all node contents

It's preferable when it makes the code simpler. When it doesn't, it isn't.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
1

Firstly: why you use shared_ptr<string> instead of string here? You shouln't do this.

1)

shared_ptr<string>

2) Use std::for_each with lambda (or range-based for loop)

for_each(upList->begin(), upList->end(), [](const shared_ptr<string>& p)
{
   cout << *p << endl;
});

or

for (const auto& p : upList)
{
   std::cout << *p << std::endl;
}
ForEveR
  • 55,233
  • 2
  • 119
  • 133