如何使用c++在数组中搜索项?

How can I search for an Item in the array using C++?

本文关键字:搜索 数组 何使用 c++      更新时间:2023-10-16

如果条目在数组中,计算它在数组中存储了多少次,以及它们各自在数组中的位置。

如何在程序中添加输出

这是我的代码…

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

取大小为15的数组location。遍历数组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 foundn" ;

添加到头部

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