【发布时间】:2018-06-25 10:07:59
【问题描述】:
我正在尝试使用 std::cout 打印一组对,但它没有编译。我在 XCode 9 上使用 C++14。错误发生在 cout<<(*it); 行
错误:二进制表达式的操作数无效('ostream'(又名'basic_ostream')和'const value_type'(又名'const std::__1::pair'))
候选函数不可行:第一个参数没有从“const value_type”(又名“const std::__1::pair”)到“const void *”的已知转换;用 & 获取参数的地址
#include <iostream>
#include <set>
#include <map>
using namespace std;
template <class P, class Q> ostream& operator<<(ostream &out, pair<P,Q>& p)
{
cout<<"["<<p.first<<","<<p.second<<"]";
return out;
}
template <class T> ostream& operator<<(ostream &out, set<T> &S)
{
cout<<"{";
for(typename set<T>::iterator it = S.begin(); it != S.end(); it++) {
cout<<(*it); //Error occurs here
if(next(it,1) != S.end()) cout<<",";
}
cout<<"}";
return out;
}
int main() {
set<pair<int,int>> s;
s.insert({1,2});
cout<<s;
return 0;
}
【问题讨论】:
-
你的重载应该通过 const 引用
std::pair。 (std::set也一样) -
另外,在循环中使用
++it而不是it++。 -
谢谢!你能告诉我 ++it 和 it++ 的区别吗?对于整数,我一直使用后缀增量。
-
@PrayanshSrivastava 参见,例如,这里:stackoverflow.com/q/1077026/580083
-
@DanielLangr:或用于范围:
cout << "{"; auto sep = ""; for (const auto& e : S) { cout << sep << e; sep = ","; } cout "}";