I have to use this struct in my code:
struct Pair
{
int x,y;
friend bool operator==(Pair a, Pair b)
{
return a.x == b.x && a.y == b.y;
}
friend istream& operator>>(istream& is, Pair& a)
{
is >> a.x >> a.y;
return is;
}
friend ostream& operator<<(ostream& os, Pair a)
{
os << '(' << a.x << ',' << a.y << ')';
return os;
}
};
I need to read a .txt file:
5 1 1 2 2 3 3 4 4 5 5
7 1 1 2 2 3 3 4 4 4 7 7 4 7 7
8 1 1 2 4 3 9 4 16 5 25 6 36 7 49 8 64
This file has 3 relations in it, each one starts with an int which is the number of pairs in that relation, then that many pairs follows. Then (if not eof) read another int and that many pairs again, and so on.
How can I read this data into my struct pair?
After I read it I will have to test if the data is reflexive, etc, but I am just having trouble getting started on this project.
Here's what I'd write.
I know my take on it is probably a bit 'advanced' - but at least it should show you that the code required is really not that much.
On bit of explanation:
using a string stream (
istringstream
) allows you to treat a single line as a stream. This isn't strictly necessary, but prevents things running awry if the input isn't in the expected format.The
friend
stream operators (in particular,operator>>
) will allow you to "just" read a pair from a stream with a simple:Now, this is what the code below implicitely does when I invoke the
copy_n
algorithm on anistream_iterator<Pair>
(i.e. it extractsPair
s in exactly the same fashion as I just showed).See it Live on Coliru with the sample input from the question, printing: