溫馨提示×

如何測試c++中is_sorted函數(shù)的正確性

c++
小樊
82
2024-09-15 18:17:26
欄目: 編程語言

要測試 C++ 中 std::is_sorted 函數(shù)的正確性,你可以創(chuàng)建一些測試用例,包括已排序和未排序的數(shù)組

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

bool test_is_sorted() {
    // 測試用例1:已排序的數(shù)組
    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:未排序的數(shù)組
    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:空數(shù)組
    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:單元素數(shù)組
    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:逆序數(shù)組
    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 的函數(shù),該函數(shù)包含了五個測試用例。每個測試用例都使用 std::is_sorted 函數(shù)來檢查給定范圍內(nèi)的元素是否已按非降序排序。如果測試用例失敗,將輸出錯誤消息并返回 false。如果所有測試用例都通過,將輸出 “All test cases passed.” 并返回 true。

main 函數(shù)中,我們調(diào)用 test_is_sorted 函數(shù)來運行測試。如果你想要添加更多的測試用例,只需在 test_is_sorted 函數(shù)中添加新的測試用例即可。

0