c++ - 调试断言在 Visual Studio 中失败,但在在线 IDE 上运行正常

标签 c++

我的代码在在线 IDE 上运行时运行良好,但在 visual studio 上运行时失败并出现调试断言错误。错误可能在 rand() 函数中,因为当我专门使用随机整数值时,它工作得很好。我不明白为什么它不在 VS 上运行。

正在显示以下消息:

Debug Assertion Failed!
Program: [Path] 
Line: 1639
Expression : sequence not ordered

另外我想问一下如何调试这些错误,因为它们没有指定特定的代码实例。

#include <iostream>
#include <list>
#include <cstdlib>          //for rand() function
using namespace std;
void display(list <int> &lst)
{
    list <int> ::iterator p;
    for (p = lst.begin(); p != lst.end(); p++)
    {
        cout << *p << " ";
    }
    cout << "\n\n";
}
int main()
{
    list <int> list1;           //empty list of zero length
    list <int> list2(5);        //empty list of size 5
    for (int i = 0; i < 3; i++)
    {
        list1.push_back(rand() % 100);
    }

    list <int> ::iterator p;

    for (p = list2.begin(); p != list2.end(); p++)
    {
        *p = (rand() % 100);
    }

    cout << "List1:  ";
    display(list1);
    cout << endl << endl;
    cout << "List2:  ";
    display(list2);
    cout << endl << endl;

    //Add two elements at the ends of list 1
    list1.push_back(200);
    list1.push_front(100);

    //Remove an element at the front of list 2
    list2.pop_front();

    cout << "Now list1:  ";
    display(list1);
    cout << "\n\n";
    cout << "Now list2:  ";
    display(list2);
    cout << "\n\n";

    list<int> listA, listB;
    listA = list1;
    listB = list2;

    //Merging two lists(unsorted)

    list1.merge(list2);
    cout << "Merged unsorted lists\n";
    display(list1);
    cout << "\n\n";

    //Sorting and merging
    listA.sort();
    listB.sort();
    listA.merge(listB);

    cout << "Merged sorted lists\n";
    display(listA);
    cout << "\n\n";

    //Reversing a list
    listA.reverse();
    cout << "Reversed merged list: \n";
    display(listA);

    return 0;
}

enter image description here

最佳答案

merge 要求对列表进行排序(参见:https://en.cppreference.com/w/cpp/container/list/merge)。在您对merge第一次 调用中,列表未排序(列表仅在您第二次 调用之前排序)。

在 Debug模式下,Microsoft C++ 标准库包括额外的运行时检查以强制执行此类不变量。 “在线 IDE”可能将 GCC 与 libstdc++ 或类似软件结合使用,它们通常不包括与 Microsoft 库相同级别的运行时检查,因此不会发现错误。

关于c++ - 调试断言在 Visual Studio 中失败,但在在线 IDE 上运行正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51220483/

相关文章:

c++ - boost::spirit::气

.net - 如何在 .NET 中对 SMTP 进行身份验证?

c++ - 共享内存指针段错误

c++ - GDB 观察实例 vector 中的类成员

c++ - 如何使用 co_return 从协程返回值?

c++ - 从 Qml 传递到 C++ 的对象类型

c++ - valgrind 是否在 Debian Wheezy 上捕捉 Qt 4.8 在极简主义应用程序中泄漏内存?

c++ - c/c++ (VS2008) 将宏参数用引号引起来

c++ - 无法将类型的非常量左值引用绑定(bind)到类型的右值

c++ - Class1 = (Class1*)pBase->next without (Class 1*) cast