Visual Studio断言在C ++集比较器上失败 [英] Visual Studio Assertion Failed on C++ set comparator

查看:152
本文介绍了Visual Studio断言在C ++集比较器上失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码在Visual Studio 2010上有一些问题,但在DevCPP上却没有.在这种情况下,我在代码中使用了C ++ STL set来插入pair<string, double>,但是随后我希望我的set使用值而不是键对它们进行排序,因此我使用了自定义比较器来实现这一点.

my code are having some problems on my Visual Studio 2010 but not on DevCPP. Heres the situation, I used C++ STL set in my code to insert pair<string, double> but then I want my set to sort them using the value instead of the key, so I used a custom comparator to achieve this.

struct sortPairSecond
{
   bool operator()(const pair<string, double> &lhs, const pair<string, double> &rhs)
   {
    return lhs.second >= rhs.second;
   }
};

该代码在DevCPP中工作正常,但使用VS2010在xtree上遇到调试断言失败.我进行了一些调试,我意识到错误是由自定义比较器中使用> =引起的,消除了=使代码正常工作,但由于我的程序中应允许重复值,因此结果不正确.因此,有人可以在这件事上帮助我吗?

The code works fine in DevCPP but encountered the Debug Assertion Failed on the xtree using VS2010. I did some debugging and I realize the error is caused by the use of >= in the custom comparator, eliminating the = make the code works but incorrect results as duplicate value should be allowed in my program. Therefore anyone can help me on this matter?

推荐答案

您使用>=而不是>可能无效,因为它必须严格排序,因此op(a,b)op(b,a)不能都为真(但如果相等的话就可以).

Your using >= and not > may be invalid because it needs to be a strict ordering thus op(a,b) and op(b,a) cannot both be true (but they would be if they were equal).

这只是一个断言错误,但set不能包含重复值.只需使用排序的vector即可,也可以使用multiset(并使用'>')

It is just an assertion error but a set cannot contain duplicate values. Just use a sorted vector or you can use multiset (and use '>')

当然,我们知道第一个值是唯一的,所以当第二个值等于第一个值时,我们可以扩展谓词.这样可以保证您具有唯一的值,然后您仍然可以使用std::set.

Of course as we know the first values are unique, we can extend the predicate when the second value is equal to compare the first. That will guarantee you unique values and then you can still use std::set.

struct sortPairSecond
{
   bool operator()(const pair<string, double> &lhs, const pair<string, double> &rhs) const
   {
    return (lhs.second > rhs.second) || (lhs.second == rhs.second && lhs.first > rhs.first) ;
   }
};

本质上,不要试图通过操纵谓词来破坏" std::set的意图.

Essentially, don't try to "break" what std::set is intended to be used for by trying to manipulate your predicate.

这篇关于Visual Studio断言在C ++集比较器上失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆