【问题标题】:ostream<<Iterator, C++ostream<<迭代器,C++
【发布时间】:2011-10-08 20:16:38
【问题描述】:

我正在尝试构建一个打印列表的运算符,
为什么 ostream

void operator<<(ostream& os, list<class T> &lst)
{
     list<T>::iterator it;
     for(it = lst.begin(); it!=lst.end(); it++)
     {
                  os<<*it<<endl; //This row
     }
}

【问题讨论】:

  • 您查看错误消息了吗?他们说了什么?
  • 欢迎来到SO,希望您阅读FAQ

标签: c++ iterator ostream


【解决方案1】:

因为*it 没有实现流插入。也就是说,operator&lt;&lt; 不存在采用 ostreamT 的重载。请注意,您应该返回 ostream&amp; os 以允许运算符链接。您的函数模板定义也看起来错误。考虑改为这样做:

template< typename T >
ostream& operator<<(ostream& os, list<T> const& lst)
{
    std::copy(
        lst.begin(), lst.end()
      , std::ostream_iterator< T >( os )
    );
    return os;
}

或者更好的是,支持各种元素和特征的流:

template< typename Elem, typename Traits, typename T >
std::basic_ostream< Elem, Traits >& operator<<(
    std::basic_ostream< Elem, Traits >& os
  , std::list<T> const& lst
)
{
    std::copy(
        lst.begin(), lst.end()
      , std::ostream_iterator< T >( os )
    );
    return os;
}

此外,您可以将分隔符传递给std::ostream_iterator 构造函数,以便在每个元素之间插入。

* 更新:* 我刚刚注意到,即使您的函数模板声明是正确的,您也会处理依赖类型。迭代器依赖于类型T,所以你需要告诉编译器:

typename list<T>::iterator it;

【讨论】:

  • 但我实际上可以像:cout的迭代器
【解决方案2】:

我认为问题出在您的模板声明中。以下应该可以编译并正常工作:

template <typename T>
void operator<<(ostream& os, list<typename T> &lst)
{
      list<T>::iterator it;
      for(it = lst.begin(); it!=lst.end(); it++)
      {
                  os<<*it<<endl;
      }
}

这当然是因为您的列表的元素类型实际上可以与ostream&lt;&lt; 运算符一起使用。

【讨论】:

    【解决方案3】:

    您以错误的方式使用模板语法:

    template<class T>
    void operator<<(ostream& os, list<T> &lst)
    {
        list<T>::iterator it;
        for(it = lst.begin(); it!=lst.end(); it++)
        {
            os<<*it<<endl; //This row
        }
    }
    

    顺便说一句,你应该返回一个对流的引用以允许输出运算符的链接,并且列表应该是const,你也可以使用标准库来做输出循环:

    template<class T>
    std::ostream& operator<<(std::ostream& os, const std::list<T> &lst)
    {
        std::copy(lst.begin(), lst.end(), std::ostream_iterator<T>(os, "\n"));
        return os;
    }
    

    【讨论】:

    • 编译器在 "list::iterator it" 行上出错,预期为 `;'在“它”之前
    • @Taru 你确定编译器知道list吗?您是否包含 并使其可见(使用 std::listusing namespace std,实际上不推荐)?
    • @TaruStolovich 是的,K-ballo 已经解决了迭代器声明问题。我总是忘记typename
    【解决方案4】:

    重写为:

    template<class T>
    ostream& operator<<(ostream& os, list<T>& lst){
        typename list<T>::iterator it;
        for(it = lst.begin(); it != lst.end(); ++it){
                     os << *it << endl;
        }
        return os;
    }
    

    【讨论】:

    • 这个答案是必要的,因为......?顺便说一句,lst 应该是 const 引用。
    猜你喜欢
    • 2017-07-04
    • 2012-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多