Sabtu, 01 Agustus 2026

C++ search in array

 

Conversation wit

#include <iostream>
#include <string>
#include <algorithm> // Required for std::for_each and std::find
#include <iterator>  // Required for std::begin and std::end

int main() {
    // 1. Array of 5 names
    std::string names[5] = {"Alice", "Bob", "Charlie", "Diana", "Ethan"};

    // 2. View all members of the array (using std::for_each from <algorithm>)
    std::cout << "Names in the array:\n";
    std::for_each(std::begin(names), std::end(names), [](const std::string& name) {
        std::cout << "- " << name << "\n";
    });
    std::cout << "\n";

    // 3. Get input from user using std::cin
    std::string targetName;
    std::cout << "Enter a name to search for: ";
    std::cin >> targetName;

    // 4. Search using std::find from <algorithm>
    auto result = std::find(std::begin(names), std::end(names), targetName);

    // 5. Output the result
    if (result != std::end(names)) {
        int index = std::distance(std::begin(names), result);
        std::cout << "Success! '" << targetName << "' was found at index " << index << ".\n";
    } else {
        std::cout << "Sorry, '" << targetName << "' was not found in the array.\n";
    }

    return 0;
}

Tidak ada komentar: