1

这会打印我的字符串的地址,而不是它的内容,

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

我的问题是:

  1. 什么ostream_iterator<shared_ptr<string>>将 shared_ptr 或字符串作为其主要对象。
  2. 如何使用这种方法打印实际的字符串内容(即印度)。
  3. 这种方法是否优于传统的 for 循环来打印所有节点内容。
4

2 回答 2

3

什么ostream_iterator<shared_ptr<string>>将 shared_ptr 或字符串作为其主要对象。

您已经为 实例化ostream_iteratorshared_ptr<string>,所以这就是它将尝试输出的内容。

如何使用这种方法打印实际的字符串内容(即印度)。

如果您出于某种原因真的想使用共享指针,那么您不能使用copy,因为这不会撤消额外的间接级别。要么使用普通循环,要么摆脱不必要的间接:

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

当然,如果没有所有的箭头、模板、新表达式和伪匈牙利疣,它看起来并不那么令人兴奋,但是任何试图维护代码的人都不会感谢您添加这些装饰。

这种方法是否优于传统的 for 循环来打印所有节点内容

当它使代码更简单时更可取。当它没有时,它不是。

于 2013-04-09T08:55:41.913 回答
1

首先:为什么你使用shared_ptr<string>而不是string这里?你不应该这样做。

1)

shared_ptr<string>

2)std::for_each与 lambda (or range-based for loop)一起使用

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

或者

for (const auto& p : upList)
{
   std::cout << *p << std::endl;
}
于 2013-04-09T08:46:08.987 回答