我需要看看数组是否在开始和结束时使用指针进行排序



实现isSorted。如果浮点数组按升序排序,该函数必须返回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++中传递指针(迭代器)时,end通常是one传递end,所以这看起来很正常。你只需要调整你的isSorted()函数,这样它就不会访问这个元素,而是在一个元素之前停止。

所以你的循环应该在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]){
//                    ^^^

重新考虑如何解决这个问题

你的指示是使用指针:

  • 1到数组中的第一个元素,
  • 将另一个元素放到最后一个元素的后面。

但你还是要使用整数索引。当你被评分时,这是行不通的。

练习的重点是而不是使用整数索引。必须只使用指针。

我可以用指针做什么?

  • 可以解引用指针来访问元素的值。
    *begin→数组的第一个元素(元素0)(与begin[0]相同)

  • 你可以在指针上添加一个,使它指向下一个元素:
    begin++→(现在' 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++中迭代器背后的概念。迭代器只是一个对象,看起来像,而作用像的指针。实际上,可以是指针。

换句话说,您已经为double数组提供了一对迭代器。使用第一个函数访问数组的元素(对其进行迭代)。你用第二秒来知道什么时候该停止。

倚在错误如前所述,"end"(或"last")迭代器并不指向最后一个元素——它指向最后一个元素的后面。换句话说,使用*end是无效的,因为它将尝试访问数组外的元素。
[-1.2] [ 8.3] [ 8.4]
↑                    ↑
begin                end

这似乎总是让人感到惊讶,但它与使用整数索引是一样的。不能访问3元素数组中的元素number3。您可以访问索引0、1和2处的元素。但不是3,因为它已经超过了数组的末尾。

--0--- --1--- --2--- --3---
[-1.2] [ 8.3] [ 8.4]

打印输出你不应该在yes/no函数中打印任何东西。函数返回一个布尔值给调用者,然后调用者决定输出什么。

那么,你的main函数应该是这样的:

#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 sortedn";
else
std::cout << "array is NOT sortedn";
}

最新更新