ToniDev

Ultima aparitie element in vector

Oct 11th, 2023
721
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.13 KB | None | 0 0
  1. #include <iostream>
  2. #include <iomanip> // 3.2131234 -> 3.21
  3. #include <cmath>  // abs()
  4. using namespace std;
  5.  
  6. int findIndex(int vector[], int vector_size, int searched_value, unsigned int times)
  7. {
  8.     int counter = 0;
  9.     int index = -1;
  10.  
  11.     for (int i = 0; i < vector_size; i++)
  12.     {
  13.         if (vector[i] == searched_value)
  14.         {
  15.             counter++;
  16.             if (counter == times)
  17.             {
  18.                 index = i;
  19.             }
  20.         }
  21.     }
  22.  
  23.     return index;
  24. }
  25.  
  26. int main() {
  27.  
  28.     int vec[] = {10, 10, 30, 40, 10, 60, 90, 80, 90};
  29.     int vec_size = sizeof(vec) / sizeof(vec[0]);
  30.     int searched_value = 0;
  31.     unsigned int times = 0;
  32.  
  33.     cout << "What value are you looking for: ";
  34.     cin >> searched_value;
  35.  
  36.     cout << "How many times do you want to find it: ";
  37.     cin >> times;
  38.  
  39.     int result = findIndex(vec, vec_size, searched_value, times);
  40.    
  41.     if (result == -1)
  42.     {
  43.         cout << "Searched element is not found or it doesn't appear " << times << " times.";
  44.         exit(1);
  45.     }
  46.     else {
  47.         cout << "Element " << searched_value << " was found at index " << result << ".";
  48.     }
  49.  
  50.     return 0;
  51. }
Advertisement
Add Comment
Please, Sign In to add comment