I realize this error is usually due to some syntax or type issues but I am not sure how to solve this problem. I think it may do with the type of findRt.
vector<triangle> findRightTriangles(unsigned long l, unsigned long h) {
<triangle> retval; // storage for return value.
triangle t;
double what;
for(t.s1 = 3; t.s1 <= h; t.s1++) {
for(t.s2 = t.s1; t.s2 <= h; t.s2++) {
what = sqrt((t.s1*t.s1) + (t.s2*t.s2));
t.s3 = static_cast<unsigned int>(what);
if(((t.s1*t.s1)+(t.s2*t.s2)) != (t.s3*t.s3)
|| t.s1+t.s2+t.s3 < l
|| t.s1+t.s2+t.s3 > h) {
continue;
}
else if(t.s1+t.s2+t.s3 <= h
&& t.s1+t.s2+t.s3 >= l
&& t.s1+t.s2 > t.s3
&& ((t.s1*t.s1)+(t.s2*t.s2)) == (t.s3*t.s3)) {
retval.push_back(t);
}
}
}
return retval;
}
int main(){
unsigned long min, max;
cin >> min >> max;
//Here is the problem:
cout << findRightTriangles(min, max) << endl;
return 0;
}
How to output the vector using cout?
For
cout
to be able to output your object you have to tell it how. One way is to overload the<<
operator:Why the error?
The compiler reports an error because there is no overloaded version of
<<
operator to handle the typevector<triangle>
which your functionfindRightTriangles()
returns.<<
is overloaded only for most of the built-in data types and not for custom classes.How to output the vector using cout?
There are two ways:
Solution 1:
A two step procedure:
Step1: You will have to iterate through the vector and
cout
each containedtriangle
.Step 2: You will have to overload
<<
for thetriangle
class as well.Solution 2:
One step Solution.
Alternately, You can overload
<<
for vector type itself:I would personally prefer the Solution 1. It is more readable & Usually more often than not one would already have an overloaded
<<
for the vector type being used and it could be leveraged.You'll have to create an overloaded version of
operator<<
forstd::cout
. It would look something like the following:and at the end of the function, you simply do a
return out;
in order to return thestd::ostream
objectout
that was passed as the first argument (in your case that will bestd::cout
).In other words, when you do
this is "syntactic sugar" for the following function call:
and would call a version of
operator<<
that looked like:If the above function was not defined, then you'd get an error like you're currently experiencing.
Operator "<<" is not overloaded for the type triangle. Have you checked this link out?
Use an iterator http://www.cplusplus.com/reference/std/iterator/.
Example would be
This assumes you have an
operator<<
for thetriangle
type.