c++:检查数组的顺序

标签 c++ arrays sorting

我尝试编写一个 bool 函数,接受一个数组和一个 bool dec。如果 dec 为真,则该函数将检查它是否下降,如果下降则返回 true。如果 dec 为 false,则函数在升序时将返回 true。

如果我用这个函数测试数组,它应该返回 false,但它给出 true,我不知道为什么。 谁能帮忙?谢谢。

#include <iostream>
#include <cstring>
#include <cmath>

#include <iomanip>

using namespace std;

bool isSorted(int array[], int size, bool dec) //false decending
{
    bool check = true;

    if (dec == false)
        for (int i = 0; i<size; i++)
            if (array[i]>array[i + 1])
            {
                check = false;
                cout << "false";
            }

    else
        for (int i = 0; i<size; i++)
            if (array[i]<array[i + 1])
                check = false;

    return check;
}


int main() {
    int n;
    bool asc=true;
    bool result;
    int arr[] = { 1, 2, 4, 3, 0 };
    n = 5;

    result = isSorted(arr, n, asc);
    cout << result;
    system("pause");
}

最佳答案

你有一个差一错误:当你到达最后一个元素并且 isize 小一个时,arrat[i+1] 正在引用数组末尾之后的元素。

由于将 check 更改为 false 是一种“单行道”,您可以通过在检测到后立即返回 false 来简化您的函数错误的订单;到达函数末尾时返回 true

您还可以将升序/降序检查移到循环内以使代码更加统一:

for (int i = 0; i < size-1 ; i++) {
    if (des && (array[i]<array[i + 1])
    || !des && (array[i]>array[i + 1])) {
        return false;
    }
}
return true;

关于c++:检查数组的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29492788/

相关文章:

javascript - 如何将 jQuery 事件处理程序应用于多个缓存选择器?

arrays - Go:多维数组的范围和长度?

java - 如何在java中对嵌套列表进行排序

c++ - 如何编写可以返回迭代器或反向迭代器的 C++ 函数

c# - 寻找 GSM 短信组件/ActiveX

c++ - 通过派生类构造函数继承访问自己的私有(private)构造函数

c++ - 从 sregex (Boost Xpressive) 中获取原始正则表达式

arrays - 标准偏差的 Swift 数组扩展

php - MySQL 中使用链接动态排序

java - Java中n类ArrayList的排序