我在名为“ 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



我可能错过了一些东西。有人可以帮我吗?

最佳答案

它不打印具有相同邻居数量的晶格数量的原因是,因为您根本没有逻辑可以查看lattices[x]是否具有与lattices[b]相同的邻居数量,因此您可以对每个不包含continue的晶格进行逻辑处理。点击lattice[x]

实际上,您尚未存储拥有的邻居数。

我建议您将代码重新组织为


从文件中读取数据一次进入整个程序中持续存在的数据结构
计算每个晶格具有的邻居数,并将该值与晶格一起存储并打印
使用存储的邻居数量完成任务

10-06 14:32