首页 > 解决方案 > 将数组索引复制到另一个数组

问题描述

我是 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;
}

如您所见,我确实在开始时定义了第二个数组。我不知道如何使用它来解决问题

任何帮助将不胜感激。非常感谢

标签: c++

解决方案


作为答案的一部分,我通常会修改 OP 的代码,但我无法理解代码中的语言。所以,我会给你基本的算法来帮助你解决你的问题,保持你尝试的代码结构完整。

  1. 让所需索引的数组为int indexes[max];

  2. 设为k当前索引indexes以跟踪插入

  3. 每次在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;
 }
}

推荐阅读