让"调试断言失败!" 用于设定比较器

sac*_*tiw 7 c++ c++-standard-library

我知道类似的问题已在此链接中得到解答帮助我修复此C++ std :: set比较器 但不幸的是我面临完全相同的问题,我无法理解它背后的原因因此需要一些帮助来解决它.

我正在使用VS2010,我的发布二进制文件运行正常没有任何问题,但调试二进制报告:

在此输入图像描述

我的比较器看起来像这样:

struct PathComp {
    bool operator() (const wchar_t* path1, const wchar_t* path2) const
    {
        int c = wcscmp(path1, path2);
        if (c < 0 || c > 0) {
            return true;
        }
        return false;
    }
};
Run Code Online (Sandbox Code Playgroud)

我的集合声明如下:

set<wchar_t*,PathComp> pathSet;
Run Code Online (Sandbox Code Playgroud)

有人可以告诉我为什么我的调试二进制文件在这个断言失败了吗?是因为我使用wcscmp()函数来比较存储在我的集合中的宽字符串吗?

提前致谢!!!

Sjo*_*erd 15

std::set需要一个行为类似于operator<或的有效comperator std::less.

std :: set代码检测到您的operator <无效,并且作为帮助您触发了您显示的断言.

事实上:你的comperator看起来像一个operator!=,而不是一个operator<

operator<应该遵循的规则之一是,a<b并且b<a不可能都是真的.在您的实现中,它是.

将您的代码更正为:

bool operator() (const wchar_t* path1, const wchar_t* path2) const
{  
  int c = wcscmp(path1, path2);
  return (c < 0);
}
Run Code Online (Sandbox Code Playgroud)

你应该没事


ltj*_*jax 9

问题是你的比较器不会导致严格的弱排序.对于"较少"的路径,它应该只返回真实 - 不是所有不同的路径.将其更改为:

struct PathComp {
    bool operator() (const wchar_t* path1, const wchar_t* path2) const
    {
        int c = wcscmp(path1, path2);
        if (c < 0) {  // <- this is different
            return true;
        }
        return false;
    }
};
Run Code Online (Sandbox Code Playgroud)

或者,仅使用c > 0也可以 - 但该组将具有相反的顺序.

算法需要知道较小和较大之间的差异才能工作,只是不等于不能提供足够的信息.如果没有小于/大于信息,则集合不可能维持订单 - 但这就是集合的全部内容.


sac*_*tiw 1

在花了更多时间之后,我们最终决定采取另一种对我有用的方法。

因此我们使用以下方法将 wchar_t* 转换为字符串:

// Converts LPWSTR to string
bool convertLPWSTRToString(string& str, const LPWSTR wStr)
{
    bool b = false;
    char* p = 0;
    int bSize;    
    // get the required buffer size in bytes
    bSize = WideCharToMultiByte(CP_UTF8,
        0,
        wStr,-1,
        0,0,
        NULL,NULL);     
    if (bSize > 0) {
        p = new char[bSize];
        int rc = WideCharToMultiByte(CP_UTF8,
            0,
            wStr,-1,
            p,bSize,
            NULL,NULL);
        if (rc != 0) {
            p[bSize-1] = '\0';
            str = p;
            b = true;
        }
    }
    delete [] p;
    return b;
}
Run Code Online (Sandbox Code Playgroud)

然后将该字符串存储在集合中,通过这样做,我不必担心比较存储的元素以确保所有条目都是唯一的。

// set that will hold unique path
set<string> strSet;
Run Code Online (Sandbox Code Playgroud)

所以我所要做的就是:

string str;
convertLPWSTRToString(str, FileName);
// store path in the set
strSet.insert(str);
Run Code Online (Sandbox Code Playgroud)

虽然我仍然不知道是什么导致我使用时出现“调试断言失败”问题a set comparator (PathComp) for set<wchar_t*,PathComp> pathSet;