c++ - 将数组索引复制到另一个数组
问题描述
我是 C++ 的初学者,试图弄清楚如何解决以下练习:
给定一个整数数组,计算一个元素在数组中出现的次数。之后,将数组索引复制到另一个数组并打印它们。换句话说,除了打印一个所选数字在数组中出现的次数之外,我还需要从第二个数组中打印该所选数字的索引(通过将它们从第一个数组复制到第二个数组)。
例子:
int myvect [ ] = {10, 42, 20, 10, 13, 20}
假设我使用键盘选择数字 10。该程序必须输出以下内容:
The chosen element is present: 2 times
The chosen element is present in the following indexes: 0, 3
输出一个元素存在多少次我没有问题。我刚刚添加了一个计数器,它工作得很好。我的问题是我不知道如何选择那些特定的索引,将它们复制到另一个数组以最终打印它们。
这是我的代码:
#include <iostream>
#define max 20
using namespace std;
int main()
{
int vett[max],n,i,num,app=0,cont=0,pos[50];
bool flag;
cout<<"inserisci un numero massimo elementi del vettore:";
cin>>n;
cout<<endl;
flag=false;
for (i=0; i<n; i++) {
cout<<"inserisci elementi del vettore:";
cin>>vett[i];
}
cout<<"inserisci elemento da trovare: ";
cin>>num;
cout<<endl;
i=0;
for (i=0; i<n; i++) {
if(vett[i]==num) {
cout<<"trovato"<<endl;
flag=true;
app=i;
cont++;
}
}
if(flag==true) {
cout<<"elemento trovato"<<endl;
if(cont>1) {
cout<<"l'elemento e' stato trovato "<< cont<<" volte"<<endl;
}
else if(cont==1) {
cout<<"l'elemento e' stato trovato "<< cont<<" volta"<<endl;
}
cout<<"Posizioni Salvate: "<<vett[i]<<endl;
}
else {
cout<<"elemento non trovato"<<endl;
}
system("pause");
return 0;
}
如您所见,我确实在开始时定义了第二个数组。我不知道如何使用它来解决问题
任何帮助将不胜感激。非常感谢
解决方案
作为答案的一部分,我通常会修改 OP 的代码,但我无法理解代码中的语言。所以,我会给你基本的算法来帮助你解决你的问题,保持你尝试的代码结构完整。
让所需索引的数组为
int indexes[max];
设为
k
当前索引indexes
以跟踪插入每次在
i
循环中找到元素时,将 的值i
插入indexes[k]
并增加 的值k
演示:
int indexes[max], k = 0;
for (int i = 0; i < n; ++i)
{
if (vett[i] == num)
{
// Do the Part 1 of your task
// This line will help you achieve the Part 2:
indexes[k++] = i;
}
}
推荐阅读
- opencv - FFMpeg v4l2m2m 绿色输出
- kubernetes - kubernetes pod 端口没有响应
- c# - 为什么添加亚克力效果后 TitleBar 标题不见了?
- laravel - 在 Laravel-update 之后尝试在 PaginatedResourceResponse.php 中获取非对象的属性“资源”
- sql-server - Django 将日期解析为 QuerySet 中的 dd-mm-yyyy
- apache - www.example.com 的主机名 SNI/HTTP 不匹配,但 example.com 不匹配
- javascript - Javascript 正则表达式,忽略一个特定字符
- c - 我们如何为方波转换器编写特定的 C 代码?或者这样做的逻辑是什么?
- networkx - 以编程方式将大量节点/边添加到 NetworkX 图的最快方法是什么?
- java - 对调用其他方法的方法使用 Mockito.when 方法作为回报