2017-07-16 79 views
0

我很難得到std :: begin()與動態分配的數組(指針),它似乎與堆棧分配一個正常工作。排序算法與動態數組編譯器錯誤

這工作:

int numbers[100]; 

// Fill array with numbers 

std::sort(std::begin(numbers), std::end(numbers)); 

這不

int* numbers = new int[10000000]; 

// Fill array with numbers 

std::sort(std::begin(numbers), std::end(numbers)); 

這裏所產生的誤差。

ptests.cpp:120:33: error: no matching function for call to ‘begin(int*&)’ 
    std::sort(std::begin(numbers), std::end(numbers)); 
           ^
ptests.cpp:120:33: note: candidates are: 
In file included from /usr/include/c++/4.8/utility:74:0, 
       from /usr/include/c++/4.8/algorithm:60, 
       from ptests.cpp:1: 
/usr/include/c++/4.8/initializer_list:89:5: note: template<class _Tp> constexpr const _Tp* std::begin(std::initializer_list<_Tp>) 
    begin(initializer_list<_Tp> __ils) noexcept 
    ^
/usr/include/c++/4.8/initializer_list:89:5: note: template argument deduction/substitution failed: 
ptests.cpp:120:33: note: mismatched types ‘std::initializer_list<_Tp>’ and ‘int*’ 
    std::sort(std::begin(numbers), std::end(numbers)); 
           ^
In file included from /usr/include/c++/4.8/string:51:0, 
       from /usr/include/c++/4.8/random:41, 
       from /usr/include/c++/4.8/bits/stl_algo.h:65, 
       from /usr/include/c++/4.8/algorithm:62, 
       from ptests.cpp:1: 
/usr/include/c++/4.8/bits/range_access.h:48:5: note: template<class _Container> decltype (__cont.begin()) std::begin(_Container&) 
    begin(_Container& __cont) -> decltype(__cont.begin()) 

是否可以將動態指針轉換爲begin()所期望的類型?任何意見,將不勝感激!

+0

包括你的錯誤的文字在你的問題。我不知道'.webp'文件是什麼。請參閱[**如何提出問題**](http://stackoverflow.com/questions/how-to-ask)和[**如何創建最小,完整和可驗證的示例**](http: //stackoverflow.com/help/mcve) –

回答

3
std::end(numbers) 

numbers變量是一個

int * 

這就是它的類型是什麼。關於這個指向一個整數的指針沒有任何意義,它告訴任何人它指向了多少個int。您將其分配爲指向10000000 int s。但是一旦你分配了它,你最終所得到的只是一個指向int的指針,除此之外別無它物。取決於你的代碼來跟蹤這個指針指向你的是什麼。您可以準確地風與相同的指針,如果你寫的,簡單地說:

int n; 

int *numbers=&n; 

numbers指針是完全一致,你所創建的一個。它只是一個指向int的指針。沒有更多,沒有更多。

std::begin()std::end()不普通指針工作,就像你指向一個int這裏,因爲,正如我剛纔所說,有大約一個指向某個對象沒有表示它有多少個連續的對象指向。它可能是一個int。它可能是兩個int s。也許是一百萬。或者,如果指針是nullptr,也許什麼都不是。

如果要排序的動態分配int陣列,只是通過開始和直接結束指針:

std::sort(number, numbers+10000000);