首頁 >後端開發 >C++ >如何在 C 數組中尋找元素?

如何在 C 數組中尋找元素?

Patricia Arquette
Patricia Arquette原創
2024-11-11 10:46:031104瀏覽

How to Find an Element in a C   Array?

如何確定 C 數組中是否存在元素

在 Java 中,使用「等於」在陣列中搜尋特定元素非常簡單方法。然而,在 C 中,「null」的概念有所不同,這需要另一種方法。

C 解: std::find

C 提供了 std ::find 演算法,在一系列元素中搜尋指定的目標值。傳回的迭代器要么指向目標(如果存在),要么指向結束迭代器(如果不存在)。

程式碼範例:

#include <iterator>
#include <algorithm>

int main() {
    Foo array[10];
    // Initialize the array here

    Foo *foo = std::find(std::begin(array), std::end(array), someObject);

    // Check if the element was found
    if (foo != std::end(array)) {
        std::cout << "Found at position " << std::distance(array, foo) << std::endl;
    } else {
        std::cout << "Not found" << std::endl;
    }

    return 0;
}

此實作有效地搜尋數組中是否存在指定元素並相應地輸出結果。

以上是如何在 C 數組中尋找元素?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn