[英]I need to see if an array is sorted using pointers on the beginning and the end
實現已排序。 如果浮點數組按升序排序,則 function 必須返回 true。 調用時,pBegin 指向數組的第一個元素,pEnd 指向最后一個元素。
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
//
//
bool isSorted(double *pBegin, double *pEnd){
int size=pEnd-pBegin;
int sum=0;
for(int i =0; i < size; i++){
if(pBegin[i] > pBegin[i+1]){
cout << "false" << endl;
return false;
}
}
cout << "true" << endl;
return true;
}
//
// Ändra INTE här nedanför!
//
int main(){
int size=3;
double arr[]={-1.2 , 8.3 , 8.4};
isSorted(&arr[0],&arr[3]);
return 0;
}
你需要改變邊界檢查,試試這個:
for(int i =0; i < size -1; i++){
if(pBegin[i] > pBegin[i+1]){
cout << "false" << endl;
return false;
}
}
你最初的陳述是錯誤的:
調用時,pBegin 指向數組的第一個元素,pEnd 指向最后一個元素。
注意這一點:
isSorted(&arr[0],&arr[3]);
元素&arr[3]
超出了數組的末尾。 所以你已經根據你的初始語句編寫了代碼,它訪問了3
元素(一個超出末尾的元素)。
我要指出的是,在 C++ 中傳遞指針(迭代器)時,結尾通常是一個傳遞結尾,所以這看起來很正常。 你只需要調整你的isSorted()
function 這樣它就不會訪問這個元素而是在之前停止一個。
所以你的循環應該在size
之前結束
for(int i =0; i < size - 1; i++){
// ^^^^^^^^
// Note: Normally `size` is correct.
// But inside the loop you accesses element `i+1`
// So you need to take that into account.
if(pBegin[i] > pBegin[i+1]){
// ^^^
您的說明是使用指針:
但是你 go 並使用 integer 索引。 當你評分時,這不會飛。
練習的重點是不使用 integer 索引。 您只能使用指針。
您可以取消引用指針以訪問元素的值。
*begin
→ 數組的第一個元素(元素0
)(與begin[0]
相同)
您可以將一個指針添加到指針以使其指向下一個元素:
begin++
→ (現在“開始”指向數組的元素1
)
您可以使用這些知識來迭代數組。
std::cout << *begin << "\n"; // print array[0]
++begin;
std::cout << *begin << "\n"; // print array[1]
++begin;
std::cout << *begin << "\n"; // print array[2]
...and so on...
問題是,你怎么知道什么時候停止?
end
指針能幫到我嗎?
這是 C++ 中迭代器背后的概念。迭代器就是一個 object,它看起來和行為都像一個指針。 事實上,它可以是一個指針。
換句話說,已經為您的double
數組提供了一對迭代器。 您使用第一個來訪問數組的元素(迭代它)。 你用第二個來知道什么時候停止。
正如已經指出的那樣,“end”(或“last”)迭代器並不指向最后一個元素——它指向最后一個元素之后的元素。 換句話說,使用*end
是無效的,因為那會嘗試訪問數組外的元素。
[-1.2] [ 8.3] [ 8.4]
↑ ↑
begin end
這似乎總是讓人感到驚訝,但這與使用 integer 索引一樣。 您不能訪問 3 元素數組的元素編號3。 您可以訪問索引 0、1 和 2 處的元素。但不能訪問 3,因為它已經超出了數組的末尾。
--0--- --1--- --2--- --3---
[-1.2] [ 8.3] [ 8.4]
你不應該從 yes/no function 中打印任何東西。function 返回一個 boolean 值給調用者,然后調用者決定打印什么。
那么,您的主要 function 應該如下所示:
#include <iostream>
#include <type_traits> // for std::extent<>
int main(){
// declare our array and get its length
double arr[] = {-1.2 , 8.3 , 8.4};
size_t size = std::extent<decltype(arr)>::value;
// determine whether the array is sorted
// and tell him/her what we learned
if (isSorted(&arr[0], &arr[size]))
std::cout << "array is sorted\n";
else
std::cout << "array is NOT sorted\n";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.