如何使用c++在数组中搜索项?
How can I search for an Item in the array using C++?
如果条目在数组中,计算它在数组中存储了多少次,以及它们各自在数组中的位置。
如何在程序中添加输出
这是我的代码…
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
相关文章:
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- 如何在动态数组上使用搜索函数
- 在 C++ 中搜索动态分配的数组中的出现次数
- 当您在此单词中搜索单词时调整字符数组的大小?
- 在对象数组中搜索字符串并返回相应值的函数
- C++线性搜索算法,确定数组中元素的数量
- 递归二进制搜索与字符串数组
- 运行搜索数组
- 比较/搜索数组中多个整数的最佳解决方案
- C 搜索数组以获取一个数字,但如果找不到该数组,则不会触发其他语句
- 更高效的是,每次都读取文件或搜索数组中的数据
- 二叉搜索数组溢出 C++
- 在c++中搜索数组中的素数
- 性能问题C++ - 搜索数组
- C++搜索数组中最大的数字
- 我需要帮助创建一个可以搜索数组的函数
- 我想要一个递归函数来检查使用二进制搜索数组的顺序
- c#到c++的转换:搜索数组
- 搜索数组以查找单词的单独实例
- 搜索数组并比较它们