How can I test for reflexive, symmetric, or transi

2019-07-29 23:15发布

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.

标签: c++
1条回答
啃猪蹄的小仙女
2楼-- · 2019-07-30 00:16

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:

    Pair p;
    stream >> p;
    

    Now, this is what the code below implicitely does when I invoke the copy_n algorithm on an istream_iterator<Pair> (i.e. it extracts Pairs in exactly the same fashion as I just showed).

using Pairs = vector<Pair>;

int main()
{
    string line;
    while (getline(cin, line))
    {
        istringstream iss(line);

        unsigned n;
        Pairs pairs;

        if (iss >> n)
            copy_n(istream_iterator<Pair>(iss), n, back_inserter(pairs));

        if (!iss)
            return 255;

        std::cout << "Read a line with " << n << " pairs (check: " << pairs.size() << ")\n";
    }
}

See it Live on Coliru with the sample input from the question, printing:

Read a line with 5 pairs (check: 5)
Read a line with 7 pairs (check: 7)
Read a line with 8 pairs (check: 8)
查看更多
登录 后发表回答