重载operator << for set

Hap*_*tal 1 c++ vector operator-overloading set

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

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;
}
Run Code Online (Sandbox Code Playgroud)

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

set<pair<int,int>> s;
cout<<s<<endl;
Run Code Online (Sandbox Code Playgroud)

它给出了错误:

cannot bind ‘std::ostream {aka std::basic_ostream<char>}’ lvalue to ‘std::basic_ostream<char>&&’
   os<<*it;
Run Code Online (Sandbox Code Playgroud)

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)
Run Code Online (Sandbox Code Playgroud)

我不知道是什么问题,错误非常神秘.此外,如果我创建一组整数并打印它,它工作正常.

Nat*_*ica 5

itin 的类型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;
}
Run Code Online (Sandbox Code Playgroud)

实例

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

  1. 你可以绑定一个临时的const &(ex函数返回)

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