如何使用C ++在数组中搜索Item?

时间:2014-06-29 08:51:49

标签: c++ arrays

如果项目在数组中,则计算它在数组中存储的次数以及它们各自的数组位置。

如何在程序中添加此输出。

这是我的代码......

int array[15]={28,3,16,4,3,16,5,8,4,12,5,4,8,21,40};
int x=0;
int done=0;
int item;

cout<<"Input an item to be searched:";
cin>>item;

while(done!=1&&x<15)
 {
  if(item==array[x])
   {
     cout<<"Found item"<<item<<" in the index of " <<x;
     done=1;
   }
  else
    {
     x++;
    }
 }
cout<<" item "<<item<<" is not found";

这应该是输出:

要搜索的项目:4
发生次数:3
阵列位置:3 8 11

3 个答案:

答案 0 :(得分:1)

获取大小为location的数组15。遍历数组array,如果找到了元素,则将该索引存储到location

int k = 0, location[15]
while(x < 15)
{
    if(item == array[x])
    {
        location[k++] = x;
    }
    x++;
}
if(k > 0)
{  
    cout << "Found item" << item << " in the index of:\n" ;
    for(int i = 0; i < k; i++)
    {
         cout << location[i] << endl;  
    }  
}
else 
     cout << "Item not found\n" ;

答案 1 :(得分:1)

将此添加到头部

int result[15]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};

尝试将以下代码插入现有的

while(x<15)
 {
  if(item==array[x])
   {
     result[x] = 1;
     // cout<<"Found item"<<item<<" in the index of " <<x;
     done++;
   }
   x++;   
 }

并显示结果

cout << "Item to be searched: " << item;
cout << "number of occurrence : " << done;
cout << "array locations : ";

x = 0;
while(x<15)
 {
  if(result[x]==1)
   {
      cout << x << ' ';
   }   
 }

答案 2 :(得分:0)

Loop through all the locations like this:
for(int i = 0; i < (sizeof(array)/sizeof(array[0]); i++) {
    if(array[i] == item) {
        count++;
        //save the locations in an array, or a string already
    }
 } cout << blabla