[英]Using std::begin and std::end with array with run-time size
對於編碼測試,我有以下 function:
static bool exists (int ints[], int size, int k)
如果k
在ints
中,目標是返回true
,否則返回false
。
使用 std 庫,可以這樣做:
static bool exists (int ints[], int size, int k) {
return std::binary_search(std::begin(ints), std::end(ints), k);
}
但是,如果編譯器知道大小,則std::begin()
僅適用於 C 風格的 arrays,據我所知。 我不確定為什么會這樣。
有沒有辦法在不編寫自定義迭代器來處理它的情況下實現我想要的? 甚至可以編寫這樣的迭代器嗎?
使用std::vector
不是一個選項,因為我無法更改 function 定義。 在調用std::binary_search()
之前將數組復制到std::vector
似乎也浪費了 CPU 時間。
您不能隨意使用std::begin()
或std::end()
,因為正如 Andrieux 在評論中指出的那樣,函數參數列表中似乎是數組類型的只是一個指針。 function 的第二個參數是元素的數量這一事實證實了這一點。 如果std::end()
所需的信息存在於ints[]
中,則不需要這樣的論點。
然而,正如我在撰寫本文時看到的前四條評論中的每一條都指出的那樣,傳入的指針是一個迭代器。 事實上,普通指針具有隨機訪問迭代器的所有屬性。
所以,是的,你不需要想出你自己的迭代器。 只需按照評論者的指示使用傳入的指針。
static bool exists (int ints[], int size, int k) {
return std::binary_search(ints, ints + size, k);
}
然而,調用std::binary_search()
是正確的做法,只有當ints[]
的元素被排序以便std::binary_search()
可以工作時。 您沒有在您的帖子中提到 state。
至於是否可以像您想要的那樣編寫迭代器,答案是“是”,但這是不必要的,因為指針已經是輸入到std::binary_search()
的正確迭代器。
你是對的,在正文中使用std::vector
會浪費時間。
如果兩個輸入數組都是有序的,並且 function 的簽名改為
template<int size> bool exists (int (&ints)[size], int k);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.