0

我在一个名为“Lattice.txt”的文件中有一组格子坐标。我下面的代码检查每个格子的邻居数-

void CheckLattice(int b)
{
   vector<Lattice> lattices;

   /* reading from file logic */
   ifstream theFile("Lattice.txt");
   double x1,y1,x2,y2;
   while (theFile >> x1 >> y1 >> x2 >> y2) {
      lattices.push_back(Lattice(x1,y1, x2,y2));
   }

   /* counting neighbors logic */
   int lattice_count = 0;
   int GroupLattice=0;
   for (int x = 0; x < lattices.size(); ++x) {
      if (lattices[b].NearestLattice(lattices[x])) {
         if (x==b) {
            continue; //this is our lattice , skip it.
         }
         lattice_count++;
      }
      GroupLattice++;
   }

   cout<<"Lattice "<<(b+1)<<" has = "<<lattice_count<<" neighbours "<<endl;
   cout << " The number of lattice with "<< lattice_count << " neighbours are " << GroupLattice << endl;
   cout << endl;

}

int main()
{
   int neighbour=0; 
   for(int i=0; i<10; i++){
      CheckLattice(i);
   }

   return 0;
}

它返回这样的值-

Lattice 1 has = 7 neighbours 
 The number of lattice with 7 neighbours are 14

Lattice 2 has = 3 neighbours 
 The number of lattice with 3 neighbours are 15

Lattice 3 has = 8 neighbours 
 The number of lattice with 8 neighbours are 14

Lattice 4 has = 6 neighbours 
 The number of lattice with 6 neighbours are 15

Lattice 5 has = 8 neighbours 
 The number of lattice with 8 neighbours are 14

Lattice 6 has = 8 neighbours 
 The number of lattice with 8 neighbours are 15

Lattice 7 has = 8 neighbours 
 The number of lattice with 8 neighbours are 14

Lattice 8 has = 1 neighbours 
 The number of lattice with 1 neighbours are 15

Lattice 9 has = 7 neighbours 
 The number of lattice with 7 neighbours are 14

Lattice 10 has = 5 neighbours 
 The number of lattice with 5 neighbours are 15

尽管此代码正确地返回了每个格子的邻居数但它不会返回具有相同数量邻居的格子总数的值。相反,它只返回 14 或 15!我该如何解决?

我想要这样的输出 -

Lattice 1 has = 7 neighbours 

Lattice 2 has = 3 neighbours 

Lattice 3 has = 8 neighbours 

Lattice 4 has = 6 neighbours 

Lattice 5 has = 8 neighbours 

Lattice 6 has = 8 neighbours 

Lattice 7 has = 8 neighbours 

Lattice 8 has = 1 neighbours 

Lattice 9 has = 7 neighbours 

Lattice 10 has = 5 neighbours 

 The number of lattice with 1 neighbours are 1
 The number of lattice with 2 neighbours are 1
 The number of lattice with 7 neighbours are 2
 The number of lattice with 8 neighbours are 4 ...etc

我可能错过了什么。任何人都可以帮助我吗?

4

1 回答 1

0

它不打印具有相同数量邻居的格子数量的原因是因为您根本没有逻辑来查看是否lattices[x]具有与 相同数量的邻居lattices[b],您只能看到每个没有击中 的格子continue

实际上,您没有存储拥有的邻居数量lattice[x]

我建议你重新组织你的代码

  • 将文件中的数据一次读入一个贯穿整个程序的数据结构
  • 计算每个格子的邻居数,并将该值与格子一起存储并打印
  • 使用存储的邻居数量来完成您的任务
于 2013-07-13T18:52:15.260 回答