c++ - 为集合重载运算符<<

标签 c++ vector set operator-overloading

我有一组整数对,我想打印它,所以我为集合和对类重载了 << 运算符:

template<typename T, typename U>
inline ostream& operator<<(ostream& os, pair<T,U> &p){
    os<<"("<<p.first<<","<<p.second<<")";
    return os;
}


template<typename T>
inline ostream& operator<<(ostream& os, set<T> &s){
    os<<"{";
    for(auto it = s.begin() ; it != s.end() ; it++){
        if(it != s.begin())
            os<<",";
        os<<*it;
    }
    os<<"}";
    return os;
}

当我创建一个集合并输出它时

set<pair<int,int>> s;
cout<<s<<endl;

它给出了错误:

cannot bind ‘std::ostream {aka std::basic_ostream<char>}’ lvalue to ‘std::basic_ostream<char>&&’
   os<<*it;

initializing argument 1 of ‘std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&&, const _Tp&) [with _CharT = char; _Traits = std::char_traits<char>; _Tp = std::pair<int, int>]’
     operator<<(basic_ostream<_CharT, _Traits>&& __os, const _Tp& __x)

我不知道是什么问题,错误很隐晦。此外,如果我创建一组整数并打印它,它就可以正常工作。

最佳答案

it 的类型在auto it = s.begin()const_iterator (source)。因此,当您调用 os<<*it;你需要一个可以接受 const 的函数 一对。如果您将代码更改为此,它将起作用:

#include <iostream>
#include <set>
#include <utility>

using namespace std;

template<typename T, typename U>
inline ostream& operator<<(ostream& os, const pair<T,U> &p){
    os<<"("<<p.first<<","<<p.second<<")";
    return os;
}


template<typename T>
inline ostream& operator<<(ostream& os, const set<T> &s){
    os<<"{";
    for(auto it = s.begin() ; it != s.end() ; it++){
        if(it != s.begin())
            os<<",";
        os<<*it;
    }
    os<<"}";
    return os;
}

int main()
{
    set<pair<int,int>> s {{1,2}};
    cout<<s<<endl;
}

Live Example

我还建议您始终将第二个参数作为 const &对于

  1. 您可以将临时绑定(bind)到 const & (前函数返回)

  2. 您不应在输出期间修改容器,因此它使用 C++ 类型系统来强制执行。

关于c++ - 为集合重载运算符<<,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31521984/

相关文章:

c++ - 如何查找是否可以通过 ShellExecute 打开文档?

c++ - Eigen 从 Affine3d 3x3 旋转矩阵中提取的四元数是否被归一化?

r - 使用 for 循环命名向量中的组件

php - 如何使用 PDO 从 SET 类型列返回多个值?

c++ - 标准 :mutex'es as members of objects that will go into containers?

c++ - 为什么 boost 正则表达式用完了堆栈空间?

c++ - 为 cublasSgemm 使用指向 vector<T>::data() 的指针

c++ - 错误 : Infinite-loop when loading elements into vector

c++ - 我该如何编码这个问题? (C++)

python - 为什么 Python 3.11 在 print(set[0]) 处不抛出错误?