Ostatnie wystąpienie danej liczby w tablicy

0

Witajcie, do napisania mam program wyświetlający ostatnie wystąpienie danej liczby w tablicy i podanie jej indeksu. Z wyświetlaniem pierwszego wystąpienia sobie poradziłem ale co tu zmienić żeby było wyświetlane ostatnie?

using namespace std;
int i, x;
int tab[]={1,2,3,4,5,6,3};
bool znajdz = false;

int main()
{
        cout << "Podaj liczbe do znalezienia: ";
        cin >> x;

        for ( i=0; i<7; i++)
        {
           if (x == tab[i])
           {
               znajdz = true;
               break;
           }
           else
           {
               znajdz = false;

           }
        }

        if (znajdz == true) cout << "1" << " O indeksie: " << i << endl;
        if (znajdz == false) cout << "0";



getch();
return 0;
}
 
0

Iteruj od końca lub nie przerywaj pętli po odnalezieniu wystąpienia.
Z tym że w tym drugim przypadku musiałbyś dodatkowo gdzieś zapisywać odnaleziony indeks.

1
#include <iostream>
#include <conio.h>
int main()
{
    using namespace std;
    int i, x;
    int tab[]={1,2,3,4,5,6,3};
    bool znajdz = false;
    cout << "Podaj liczbe do znalezienia: ";
    cin >> x;
        for ( i=6; i>0; i--)
        {
           if (x == tab[i])
           {
               znajdz = true;
               break;
           }
           else
           {
               znajdz = false;

           }
        }
        if (znajdz == true) cout << "1" << " O indeksie: " << i << endl;
        else cout << "0";
getch();
return 0;
}
0
#include <iostream>
#include <vector>

using numbers_t = std::vector<int>;
void findIndex(numbers_t const& numbers, int number);

int main()
{
    numbers_t numbers { 7, 1, 2, 3, 1, 4, 3, 1, 4, 1 };
    findIndex(numbers, 1);
    findIndex(numbers, 7);
    findIndex(numbers, 6);
    findIndex(numbers, 2);

    return 0;
}

void findIndex(numbers_t const& numbers, int number)
{
    int pos = -1;
    auto v_size = numbers.size();
    if(!v_size) {
        return;
    }

    for(auto i = static_cast<int>(v_size) - 1 ; i >= 0 ; --i) {
        if(numbers[i] == number) {
            pos = i;
            break;
        }
    }

    if(pos != -1) {
        std::cout << pos << std::endl;
    } else {
        std::cout << "Nothing found.\n";
    }
}

http://melpon.org/wandbox/permlink/NsdcSsOeP01JroPJ

0
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
 
int main()
  {
   vector<int> numbers { 7, 1, 2, 3, 1, 4, 3, 1, 4, 1 };
   auto it=find(numbers.rbegin(),numbers.rend(),4);
   if(it==numbers.rend()) cout<<"Nie znaleziono"<<endl;
   else cout<<"pos "<<numbers.size()-1-(it-numbers.rbegin())<<endl;
   return 0;
  }

1 użytkowników online, w tym zalogowanych: 0, gości: 1