gpt4 book ai didi

C++ std::sort() - 无法对访问成员变量的类类型的 vector 进行排序

转载 作者:太空宇宙 更新时间:2023-11-04 15:15:50 24 4
gpt4 key购买 nike

Entry.h:

//returns the sum of all non mega entry percentages
float sumOfNonMegaEntryPct(vector<Number>& arg1_Numbers);

Entry.cpp:

//returns the sum of all mega entry percentages
float Entry::sumOfMegaEntryPct(vector<MegaNumber>& arg1_MegaNumbers)
{
float sumPct = 0.00f;
for (MegaNumber c : megaEntry)
{
sumPct = sumPct + arg1_MegaNumbers[c.getID()].getOccurencePct();
}

return sumPct;
}

Lotto.h:

public:
//compares two entries, used for sorting algorithm, sorts by nonmega number
bool compareEntry_sumPct_nonMega(Entry arg1, Entry arg2);

protected:
vector<Numbers> numbers;
vector<MegaNumbers> megaNumbers;

Lotto.cpp:

#include "lotto.h"

//sorts nonmega numbers by sum of their pct, used for sort algorithm
bool Lotto::compareEntry_sumPct_nonMega(Entry arg1, Entry arg2)
{
bool b = arg1.sumOfNonMegaEntryPct(numbers) < arg2.sumOfNonMegaEntryPct(numbers);
return b;
}

源代码.cpp:

vector<Entry> copyGameEntry = game.getPlayEntry();
sort(copyGameEntry.begin(), copyGameEntry.end(),
bind(&Lotto::compareEntry_sumPct_nonMega, game));

这只是代码的一部分,但我认为这足以说明问题。编译时出现错误:

Severity Code Description Project File Line Error C2451 conditional expression of type 'std::_Unforced' is illegal Lottery Sort e:\program files (x86)\microsoft visual studio 14.0\vc\include\algorithm 3133

Severity Code Description Project File Line Error C2675 unary '!': 'std::_Unforced' does not define this operator or a conversion to a type acceptable to the predefined operator Lottery Sort e:\program files (x86)\microsoft visual studio 14.0\vc\include\algorithm 3118

问题:

可能是什么问题?

最佳答案

您错误地使用了 std::bind。您需要为未绑定(bind)的参数使用占位符:

using namespace std::placeholders;
sort(copyGameEntry.begin(), copyGameEntry.end(),
bind(&Lotto::compareEntry_sumPct_nonMega, game, _1, _2));

注意此绑定(bind)表达式将复制 game 对象,因此您应该使用 std::ref(game) 或仅使用 &game 来避免不必要的复制。

或者使用 lambda 函数:

sort(copyGameEntry.begin(), copyGameEntry.end(),
[&game](Entry& l, Entry& r) {
return game.compareEntry_sumPct_nonMega(l, r);
});

关于C++ std::sort() - 无法对访问成员变量的类类型的 vector 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33449295/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com