Algoritma Panelusuran Multiple-Item (Multiple-Item Search) ing C++- Panjelasan, Conto, lan Kode

Algoritma telusuran macem-macem item digunakake kanggo nemokake kabeh kedadeyan saka unsur tartamtu ing dhaptar. Ora kaya algoritma panelusuran item siji, pendekatan iki nglacak pirang-pirang kedadeyan saka unsur target lan ngasilake dhaptar posisi.

Cara Kerjane

  1. Miwiti saka wiwitan dhaptar.
  2. Ulangi saben unsur ing dhaptar.
  3. Bandhingake unsur saiki karo nilai target.
  4. Yen unsur saiki padha karo nilai target, cathet posisine.
  5. Terusake menyang unsur sabanjure lan baleni langkah 3-4.
  6. Sawise ngulang kabeh dhaptar, bali dhaptar posisi sing direkam.

Tuladha

Ayo nimbang dhaptar integer lan kita pengin nemokake kabeh kedadeyan nomer 23.

Dhaptar: {12, 23, 45, 23, 56, 23, 89, 90}

  1. Mulai saka awal: 12. Ora nomer sing dikarepake.
  2. Pindhah menyang unsur sabanjure: 23. Cocokake ditemokake, rekam posisi minangka 1.
  3. Pindhah menyang unsur sabanjure: 45. Ora nomer sing dikarepake.
  4. Pindhah menyang unsur sabanjure: 23. Cocokake ditemokake, rekam posisi minangka 3.
  5. Pindhah menyang unsur sabanjure: 56. Ora nomer sing dikarepake.
  6. Pindhah menyang unsur sabanjure: 23. Cocokake ditemokake, rekam posisi minangka 5.
  7. Pindhah menyang unsur sabanjure: 89. Ora nomer sing dikarepake.
  8. Pindhah menyang unsur sabanjure: 90. Ora nomer sing dikarepake.
  9. Sawise iterasi, bali dhaptar posisi: [1, 3, 5].

Tuladha Kode ing C++

#include <iostream>  
#include <vector>  
  
std::vector<int> multipleItemSearch(const std::vector<int>& arr, int target) {  
    std::vector<int> positions;  
  
    for(int i = 0; i < arr.size(); ++i) {  
        if(arr[i] == target) {  
            positions.push_back(i);  
        }  
    }  
  
    return positions;  
}  
  
int main() {  
    std::vector<int> numbers = {12, 23, 45, 23, 56, 23, 89, 90};  
    int target = 23;  
  
    std::vector<int> result = multipleItemSearch(numbers, target);  
  
    std::cout << "Occurrences of " << target << " found at positions: ";  
    for(int pos: result) {  
        std::cout << pos << ";  
    }  
    std::cout << std::endl;  
  
    return 0;  
}  

Ing conto sing diwenehake, multipleItemSearch fungsi kasebut digunakake kanggo nemokake kabeh kedadeyan nomer 23 ing dhaptar integer. Asil bakal dadi vektor sing ngemot posisi kabeh kedadeyan(posisi diwiwiti saka 0).