#
#include <string>
#include <array>
#include <algorithm>
int main() {
// 1. Declare and initialize an array of 5 names
std::array<std::string, 5> names = {"Alice", "Bob", "Charlie", "Diana", "Ethan"};
// 2. Specify the name to search for
std::string target = "Charlie";
// 3. Search using std::find from <algorithm>
auto it = std::find(names.begin(), names.end(), target);
// 4. Check if the name was found
if (it != names.end()) {
// std::distance calculates the index from the iterator
int index = std::distance(names.begin(), it);
std::cout << "Found '" << target << "' at index " << index << "!\n";
} else {
std::cout << "'" << target << "' was not found in the array.\n";
}
return 0;
}
Key Takeaways
std::find(begin, end, value): Iterates through the collection and returns an iterator pointing to the first matching element. If no match is found, it returnsnames.end().std::array: Preferred over raw C-style arrays (std::string names[5]) because it works seamlessly with C++ standard algorithms likestd::find.std::distance: Converts the resulting iterator into a standard0-based array index.

Tidak ada komentar:
Posting Komentar