0

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

3
  • 1
    Use std::count and std::find instead of rolling out your own version of them. Commented Mar 17, 2020 at 10:18
  • could you tell me how should i use it? Commented Mar 17, 2020 at 10:23
  • 1
    std::count std::find Commented Mar 17, 2020 at 10:29

5 Answers 5

1

I usually make modifications to the OP's code as a part of my answer, but I cannot understand your language in the code. So, I will give you the basic algorithm to help you solve your problem keeping the structure of your attempted code intact.

  1. Let the array of required indexes be int indexes[max];

  2. Let k be the current index of indexes to keep track of the insertion

  3. Each time you find the element in your i loop, insert the value of i into indexes[k] and increment the value of k

Demo:

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;
 }
}
Sign up to request clarification or add additional context in comments.

2 Comments

I wrote a few lines in Italian. Sorry for that
@alex108 No worries, let me know if I should edit my answer anywhere
1

You could use std::find

An example:

std::array<int, 5> data{10, 2, 3, 4, 10};
std::vector<int> indices;
int num = 10;

auto it = data.begin();
while ((it = std::find(it, data.end(), num))!= data.end())
{
    indices.push_back(std::distance(data.begin(), it));
    it++;
}

indices then contains the indices of the elements that match your search criterion.

3 Comments

You can directly use std::find(it, data.end(), num). Otherwise, you need to capture num.
Thanks, just added the capturing
Why not std::find though? It's designed precisely for this purpose. Using std::find_if is adding unnecessary verbosity here.
1

In your loop:

for (i=0; i<n; i++) {

    if(vett[i]==num) {

        cout<<"trovato"<<endl;
        flag=true;
        app=i;
        cont++;
    }

}

You are trying to test if number at index i is your desired number. Well, what about storing that i index into another array everytime the condition is true.

// create array with the same size as input array

int found_indexes[max];
size_t current_position = 0;

// now your loop

for (i=0; i<n; i++) {

    if(vett[i]==num) {

        cout<<"trovato"<<endl;
        flag=true;
        app=i;
        cont++;

        // save index at current position and advance by one after saving

        found_indexes[current_position++] = i;
    }

}

// at the end print all indexes from array
// this is done by printing all values until we meet with current_position index

if (current_position == 0)
    cout << "No indexes found.\n";
else
{
    // Printing spaces somewhat nicely.

    cout << found_indexes[0];
    for(size_t i = 1; i < current_position; i++)
        cout << ' ' << found_indexes[i];
}

Comments

1

I think you are trying to do that

#include <iostream>
#include <stdlib.h>
#define max 20

using namespace std;

int main()
{
int vett[max],n,i,num,cont=0,pos[50];
bool flag;

cout<<"Enter how many numbers:";
cin>>n;

cout<<endl;
flag=false;

for (i=0; i<n; i++)
{
    cout<<"Enter "<<i+1<<" Element:";
    cin>>vett[i];
}

cout<<"\nEnter what to find: ";
cin>>num;
cout<<endl;

for (i=0; i<n; i++)
{
    if(vett[i]==num)
    {
        flag=true;
        pos[cont++]=i;
    }
}

if(flag==true)
{

   cout<<"The chosen element is present:"<<cont<<" times"<<endl;
   cout<<"The chosen element is present in the following indexes:";
   for(i=0;i<cont;i++)
   cout<<pos[i]<<",";    //it prints a number followed by a comma.
   cout<<endl;
}
else
   cout<<"No Element"<<endl;


system("pause");
return 0;
}

Output:

Enter how many numbers:6

Enter 1 Element:10
Enter 2 Element:42
Enter 3 Element:20
Enter 4 Element:10
Enter 5 Element:13
Enter 6 Element:20

Enter what to find: 10

The chosen element is present:2 times
The chosen element is present in the following indexes:0,3,
Press any key to continue . . .

Process returned 0 (0x0)   execution time : 29.955 s
Press any key to continue.   

Edit:

if you did not want comma after last element use this

  for(i=0;i<cont;i++)
  {
      cout<<pos[i];
      if((i+1)!=cont)
       cout<<",";
  }

3 Comments

@alex108 if you get the answer feel free to accept any of the 5 answers.
I don't understand why it prints the first index in the same line while the other indexes are printed in the next line
@alex108 all indexes are printed in same line followed by a comma
1

I think that the appropriate data structure here is std::map<int, std::set<int> > which is the hash map representing the value mapped to the set of indices where this value is present. The size of set tells you the number of occurrences of the particular value. Simple implementation might look like this:

std::map<int, std::set<int> > values_to_indices;
for (int i = 0; i < input_array.size(); i++)
{
  values_to_indices[input_array[i]].insert(i);  // we can use operator[] because when element is not yet in the map, std::set will be default constructed
}

for (auto elem : values_to_indices)
{
  std::cout << "element: " << elem.first << " is repeated " << elem.second.size() << " times\n";
  // here you can also print std set of indices of that element
}

This doc explains that using operator[] on the map constructs the element if it was not present before. The values in the set are guaranteed to be unique because we iterate once from 0 to input array size.

=== EDIT ===

As suggested in the comment, instead of int you might use size_t as a type representing indices:

std::map<int, std::set<size_t> > values_to_indices;
for (size_t i = 0; i < input_array.size(); i++)
{
  values_to_indices[input_array[i]].insert(i);
}

Just be aware of unsigned integer underflow if later you plan to do some things with that indices.

1 Comment

+1 for STL approach, but I would recommend std::map<int, std::set<std::size_t> >, i.e. using std::size_t and not int to represent the indices.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.