如何检查数组中是否存在值或返回下一个空闲索引

时间:2015-10-27 02:59:13

标签: c arrays

我试图编写一个有效的函数,它将值作为输入并检查数组中的值。如果数组中存在值,则返回该数组中该值的索引。否则,如果值不存在,则返回数组中的下一个空闲索引。 在main函数中,我想通过getIndex()写入以下索引之一返回   - 在getIndex返回的索引处   - 或下一个免费索引。

#include <stdio.h>

typedef struct Section {
int numOfStudents;
} Section;


typedef struct School {
   int schoolId;
   int numberofSections;
   Section sections[5];
} School;

School school_1[4]; // array that hold the values

int getIndex(int  schoolAddressInfo)
{
  int empty_index[4] = {-1,-1,-1,-1}; //array to hold next free index
  int rIndex = -1; // index to return
  int i,j,k;

  for ( i = 0; i < 4; i++)
  { 
    if (school_1[i].schoolId == 0) // if the index in array school_1 doesn't contain any data i.e default value = 0, mark that index
    {
      empty_index[i] = i;
    }
    else if (school_1[i].schoolId == schoolAddressInfo) // check if value exist in an array, if it does return the index
    {
      rIndex = i;
      return rIndex;      
      break; // break once element found, don't need to go through rest of the array
    }   
  } 
  // if the value is not found, return first free index out of indexs saved in empty_index
  for ( j = 0; j < 4; j++)
  { 
    if (empty_index[j] != -1)
    {
      rIndex = empty_index[j];    
      return rIndex;      
      break;
    }
  }  
  return rIndex;
}

//function to populate the array that hold values i.e school_1[]
void populateSchool(){
    int i,j;
    for(i=0; i < 4; i++)
    {
       school_1[i].schoolId = 0;
       school_1[i].numberofSections = 0;
       for (j=0;j<5;j++){
         school_1[i].sections[j].numOfStudents = 0;
        }

    }
    school_1[0].schoolId = 21;
    school_1[1].schoolId = 22;
    school_1[3].schoolId = 23;
   }

int main ()
{
  int i,y,z;
  int schoolId = 25;
  populateSchool(); //populate the array with either default or real values
  int index = getIndex(schoolId); //check if schoolId already exist, if it doesn't exist, create new index, else update existing index

  for (i=0; i< 5; i++)
  {
    school_1[index].sections[i].numOfStudents = 20;
  }

  for ( y = 0; y < 5; y++ )
  {
    printf("school_1[%d].sections[%d].numOfStudents= %d\n",     index,y,school_1[index].sections[y].numOfStudents );
  }
   return 0;
}

此代码有效,但我想知道是否可以进一步优化getIndex()。 例如,在不使用2 for循环的情况下获得相同的结果。

1 个答案:

答案 0 :(得分:0)

一种可能的方法,而不必使用另一个for循环

int getIndex(int  schoolAddressInfo)
{
  int rIndex = -1; // index to return
  int i;
  bool firstFreeIndexFound = false;

  for ( i = 0; i < 4; i++)
  { 
    if (school_1[i].schoolId == schoolAddressInfo) // check if value exist in an array, if it does return the index
    {
      rIndex = i;
      return rIndex; //don't need to go through rest of the array   
    }
    else if (school_1[i].schoolId == 0 && firstFreeIndexFound!=true) // if the index in array school_1 doesn't contain any data i.e default value = 0, mark that index
    {
      rIndex = i;
      firstFreeIndexFound = true;
    }
  }  
  return rIndex;
}