I'm trying to print a set of pairs using std::cout, but it's not compiling. I'm using C++14 on XCode 9. The error occurs on cout<<(*it);
line
Error: Invalid operands to binary expression ('ostream' (aka 'basic_ostream') and 'const value_type' (aka 'const std::__1::pair'))
Candidate function not viable: no known conversion from 'const value_type' (aka 'const std::__1::pair') to 'const void *' for 1st argument; take the address of the argument with &
#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;
}
std::pair
by const reference. (same forstd::set
) – Jarod42++it
instead ofit++
in the loop. – Daniel Langrcout << "{"; auto sep = ""; for (const auto& e : S) { cout << sep << e; sep = ","; } cout "}";
– Jarod42