Program in C++
. I sorted a vector using STL sort and the boolean comparator (here, cmp1
and cmp2
functions). However, upon running the program and reading the values of the vector, it returns:
Debug Assertion Failed!, Line:1618, Expression: invalid comparator
. Here, the function that returns the error from the algorithm library is:
// FUNCTION TEMPLATE _Debug_lt_pred
template <class _Pr, class _Ty1, class _Ty2,
enable_if_t<is_same_v<_Remove_cvref_t<_Ty1>, _Remove_cvref_t<_Ty2>>, int> = 0>
constexpr bool _Debug_lt_pred(_Pr&& _Pred, _Ty1&& _Left, _Ty2&& _Right) noexcept(
noexcept(_Pred(_Left, _Right)) && noexcept(_Pred(_Right, _Left))) {
// test if _Pred(_Left, _Right) and _Pred is strict weak ordering, when the arguments are the cv-same-type
const auto _Result = static_cast<bool>(_Pred(_Left, _Right));
if (_Result) {
_STL_VERIFY(!_Pred(_Right, _Left), "invalid comparator");
}
return _Result;
}
template <class _Pr, class _Ty1, class _Ty2,
enable_if_t<!is_same_v<_Remove_cvref_t<_Ty1>, _Remove_cvref_t<_Ty2>>, int> = 0>
constexpr bool _Debug_lt_pred(_Pr&& _Pred, _Ty1&& _Left, _Ty2&& _Right) noexcept(noexcept(_Pred(_Left, _Right))) {
// test if _Pred(_Left, _Right); no debug checks as the types differ
return static_cast<bool>(_Pred(_Left, _Right));
}
This is my program:
#include <iostream>
#include <algorithm>
#define DIM 10006
using namespace std;
bool cmp1(int st, int dr) {
return (st >= dr);
}
bool cmp2(int st, int dr) {
return (st <= dr);
}
void Scan(int& n, int& m, char& c, int v[])
{
cin >> n >> m >> c;
for (int i = 0; i < n * m; i++)
cin >> v[i];
}
void Print(int n, int m, int v[])
{
int k = 0;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
cout << v[k] << ' ';
k++;
}
cout << '\n';
}
}
int main()
{
int v[DIM];
int n, m;
char c;
Scan(n, m, c, v);
if (c == '+')
sort(v, v + n * m, cmp1);
else //c == '-'
sort(v, v + n * m, cmp2);
Print(n, m, v);
return 0;
}