【问题标题】:Unable to execute std::sort correctly无法正确执行 std::sort
【发布时间】:2017-09-30 05:20:22
【问题描述】:

在做了一些研究后,我辞职想问std::sort 出了什么问题。

根据 here 的 Oliver Charlesworth 建议,我创建了一个比较,包括算法标题并在我的函数中调用 std::sort。我仍然收到错误。可能是疏忽,但仍然如此。

错误:

错误 C2780 void std::sort(_RanIt,_RanIt)':需要 2 个参数 - 提供了 3 个

错误 C2672 'std::sort':找不到匹配的重载函数

错误 C3867 'ImageEvaluator::comparator':非标准语法;使用 '&' 创建指向成员的指针

结构:

struct numLocWidth
{
    int width;
    int number;
    int location;
};

比较:

bool comparator(const numLocWidth &a, const numLocWidth &b) 
{ 
    return a.location < b.location; 
}

功能:

if (tempMax > minAcceptableValue)
{
    tempLocAndVal.location = max_Pot_Loc.x;
    tempLocAndVal.number = i - 1;
    tempLocAndVal.width = templates[7][i].size().width;
    foundNumbers.push_back(tempLocAndVal);
    std::sort(foundNumbers.begin(), foundNumbers.end(), comparator);                
}

不知道这里发生了什么,我一直在摸不着头脑。我可以编写自己的排序函数,但我很确定这种方式会更有效。

【问题讨论】:

  • 看起来comparator 是一个非静态类成员函数。使其成为静态或非成员。
  • 请看MCVE
  • 您没有提供足够的信息。从错误消息来看,您的 comparator() 似乎是某个类的非静态成员函数。 std::sort() 的变体接受比较器作为第三个参数,要求比较器是二进制函数(即,类的静态成员或接受所需参数的非成员函数)。
  • 谢谢你们俩。请提出您的答案,以便我标记为已解决。

标签: c++ sorting c++11


【解决方案1】:

正如 VTT 和 Peter 正确指出的那样,我的比较需要标记为静态,因为它是一个类的成员。

更多信息可以在here 在需求和BinaryPredicates 下找到。

感谢您的帮助

解决方案。 来自:

bool comparator(const numLocWidth &a, const numLocWidth &b) 
{ 
    return a.location < b.location; 
}

收件人:

static bool comparator(const numLocWidth &a, const numLocWidth &b) 
{ 
    return a.location < b.location; 
}

再次感谢您的帮助

【讨论】:

    猜你喜欢
    • 2022-08-18
    • 2013-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-27
    • 1970-01-01
    • 2021-12-15
    相关资源
    最近更新 更多