I am a beginner in C++ trying to figure out how I could solve the following exercise:
Given an array of whole numbers, count how many times one element is present in the array. After that, copy the array indexes to another array and print them. In other words, apart from printing the amount of times one chosen number is present in the array, I need to print the indexes of that chosen number from a second array (by copying them from the first array to the second).
Example:
int myvect [ ] = {10, 42, 20, 10, 13, 20}
Assuming I choose the number 10 using the keyboard. The program will have to output the following:
The chosen element is present: 2 times
The chosen element is present in the following indexes: 0, 3
I don't have problems outputting how many times one element is present. I just added a counter and it works perfectly. My problem is i don't know how to select those specific indexes, copy them to another array to finally print them.
Here is my code:
#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;
}
As you can see, I did define a second array in the beginning. I don't know how to use it to solve the problem
Any help will be appreciated. Thank you very much
std::countandstd::findinstead of rolling out your own version of them.std::countstd::find