温馨提示×

如何测试c++中is_sorted函数的正确性

c++
小樊
82
2024-09-15 18:17:26
栏目: 编程语言

要测试 C++ 中 std::is_sorted 函数的正确性,你可以创建一些测试用例,包括已排序和未排序的数组

#include <iostream>
#include <vector>
#include <algorithm>

bool test_is_sorted() {
    // 测试用例1:已排序的数组
    std::vector<int> sorted_array = {1, 2, 3, 4, 5};
    if (!std::is_sorted(sorted_array.begin(), sorted_array.end())) {
        std::cerr << "Test case 1 failed: sorted array" << std::endl;
        return false;
    }

    // 测试用例2:未排序的数组
    std::vector<int> unsorted_array = {1, 3, 2, 4, 5};
    if (std::is_sorted(unsorted_array.begin(), unsorted_array.end())) {
        std::cerr << "Test case 2 failed: unsorted array" << std::endl;
        return false;
    }

    // 测试用例3:空数组
    std::vector<int> empty_array = {};
    if (!std::is_sorted(empty_array.begin(), empty_array.end())) {
        std::cerr << "Test case 3 failed: empty array" << std::endl;
        return false;
    }

    // 测试用例4:单元素数组
    std::vector<int> single_element_array = {42};
    if (!std::is_sorted(single_element_array.begin(), single_element_array.end())) {
        std::cerr << "Test case 4 failed: single element array" << std::endl;
        return false;
    }

    // 测试用例5:逆序数组
    std::vector<int> reversed_array = {5, 4, 3, 2, 1};
    if (std::is_sorted(reversed_array.begin(), reversed_array.end())) {
        std::cerr << "Test case 5 failed: reversed array" << std::endl;
        return false;
    }

    // 所有测试用例通过
    std::cout << "All test cases passed." << std::endl;
    return true;
}

int main() {
    test_is_sorted();
    return 0;
}

这个示例代码首先定义了一个名为 test_is_sorted 的函数,该函数包含了五个测试用例。每个测试用例都使用 std::is_sorted 函数来检查给定范围内的元素是否已按非降序排序。如果测试用例失败,将输出错误消息并返回 false。如果所有测试用例都通过,将输出 “All test cases passed.” 并返回 true

main 函数中,我们调用 test_is_sorted 函数来运行测试。如果你想要添加更多的测试用例,只需在 test_is_sorted 函数中添加新的测试用例即可。

0