[英]std::begin and std::end not working with pointers and reference why?
為什么std :: begin()和std :: end()適用於數組而不是指針[幾乎是數組]和數組的引用[它是原始數組的別名]。
在我撓頭15分鍾后,我無法在谷歌中得到任何東西。
下面只有第一個案例,而不是第二個和第三個,這可能是什么原因?
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
int main()
{
int first[] = { 5, 10, 15 }; // Fist Case
if (std::find(std::begin(first), std::end(first), 5) != std::end(first)) {
std::cout << "found a 5 in array a!\n";
}
int *second = new int[3]; // Second Case
second[0] = 5;
second[1] = 10;
second[2] = 15;
if (std::find(std::begin(second), std::end(second), 5) != std::end(second)) {
std::cout << "found a 5 in array a!\n";
}
int *const&refOfFirst = first; // Third Case
if (std::find(std::begin(refOfFirst), std::end(refOfFirst), 5) != std::end(refOfFirst)) {
std::cout << "found a 5 in array a!\n";
}
}
錯誤:
error: no matching function for call to ‘begin(int&)’
if (std::find(std::begin(*second), std::end(*second), 5) != std::end(*second)) {
^
只給出一個指向數組開頭的指針,就無法確定數組的大小; 所以begin
和end
不能用於指向動態數組的指針。
如果需要一個知道其大小的動態數組,請使用std::vector
。 作為獎勵,這也將修復您的內存泄漏。
第三種情況失敗,因為您再次使用(引用)指針。 您可以使用對數組本身的引用:
int (&refOfFirst)[3] = first;
或者,為了避免必須指定數組大小:
auto & refOfFirst = first;
並begin
和end
會在這方面努力,正是因為他們將努力在first
本身。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.