使用结构的自反,对称或传递的测试集

时间:2017-03-01 04:10:25

标签: c++

我的代码中有这个结构

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;
 }
};

int main(){
Pair p;
fstream file;
string fileName = "Text.txt";
file.open(fileName.c_str(), fstream::in);
if(!file){
    cout << "Could Not Open " << fileName << " File" << endl;
}else{
    int size = 43;
    int * myArray = new int[size];
    for(int i = 0; i < size; i++){
        file >> myArray[i];
    }
    printArray(myArray,size);
}
return 0;

}

从文本文件中读取

  

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

这个文件中有3个关系,每个关系以一个int开头,这是该关系中的对数,然后是许多对。然后(如果不是eof)再次读取另一个int和那么多对,依此类推。

如何将这些数据读入我的结构对?

1 个答案:

答案 0 :(得分:0)

或多或少这样的事情:

#include <fstream>
#include <iostream>
#include <list>
#include <vector>

struct Pair
{
    int x,y;
    friend bool operator==(Pair a, Pair b)
    {
        return a.x == b.x && a.y == b.y;
    }
    friend std::istream& operator>>(std::istream& is, Pair& a)
    {
        is >> a.x >> a.y;
        return is;
    }
    friend std::ostream& operator<<(std::ostream& os, Pair a)
    {
        os << '(' << a.x << ',' << a.y << ')';
        return os;
    }
};

int main()
{
    std::fstream file;
    file.open("Text.txt", std::fstream::in);

    std::list<std::vector<Pair> > relations;
    int size = 0;
    while(file >> size)
    {
        relations.emplace_back(size);
        for(int i=0; i < relations.back().size() && file >> relations.back()[i]; i++);
    }

    //Print
    for(auto &r : relations)
    {
        std::cout << "[";
        for(auto &p : r)
        {
            std::cout << p;
        }
        std::cout << "]\n";
    }

    return 0;
}

Example

相关问题