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

时间:2011-04-28 18:44:49

标签: c++ c++-standard-library

我知道此链接已回答类似问题Help me fix this C++ std::set comparator 但不幸的是我面临完全相同的问题,我无法理解其背后的原因因此需要一些帮助来解决它。

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

enter image description here

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

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;
    }
};

我的设置声明如下:

set<wchar_t*,PathComp> pathSet;

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

提前致谢!!!

3 个答案:

答案 0 :(得分:15)

std::set需要一个行为类似于operator<std::less的有效编译器。

std :: set代码检测到您的运营商&lt;是无效的,并且作为帮助你触发了你展示的断言。

确实:你的comperator看起来像operator!=,而不是operator<

operator<应遵循的规则之一是,a<bb<a不能同时为真。在您的实现中,它是。

将您的代码更正为:

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

你应该没事。

答案 1 :(得分:9)

问题是您的比较器不会导致严格弱的排序。对于“较少”的路径,它应该只返回true - 不是所有不同的路径。将其更改为:

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;
    }
};

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

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

答案 2 :(得分: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;
}

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

// set that will hold unique path
set<string> strSet;

所以我所要做的就是:

string str;
convertLPWSTRToString(str, FileName);
// store path in the set
strSet.insert(str);

虽然我在使用a set comparator (PathComp) for set<wchar_t*,PathComp> pathSet;

时仍然不知道导致“Debug Assertion Failed”问题的原因