gpt4 book ai didi

c++ - 在 C++ 中重载比较运算符导致 "invalid operator<"

转载 作者:可可西里 更新时间:2023-11-01 18:26:52 25 4
gpt4 key购买 nike

目前正在尝试在 C++ 中对对象 vector 进行排序,每个对象包含一个字符串

字符串可以包含字母或数字(由于设计限制,这是必要的,因为比较器可以更改)。

此时重载对象的类,这样当比较两个对象时,比较的是它们包含的字符串。这在一定程度上起作用——但是,当我使用排序操作(例如 STL 排序)对对象进行排序时,它将按顺序对三个字符串(例如“1”、“4”、“12”)进行排序“1”、“12”、“4”。 4 大于 12,但因为它从最左边的数字开始比较,所以会出现这种“不正确”的排序。

我最初的 react 是改变我重载比较操作的方式。我会首先检查我正在比较的字符串的长度——如果字符串的内容更大或更小,这将是一个明显的迹象。

// overloaded comparision operators
friend bool operator<(const nodeRecord & record1, const nodeRecord & record2){
// we need to deal with strings of different lengths...
if(record1.comparator.length() < record2.comparator.length())
return true;
else
return (record1.comparator < record2.comparator);
}

此操作会在运行时产生“表达式:无效运算符<”消息。

关于我在哪里犯错有什么想法吗?看来我应该能够准确地指示操作我希望排序操作如何发生——即使它是无效的,因为我目前正在使用一个 vector 来包含对象。

nodeRecord 对象初始化期间的比较器:

nodeRecord(int fromNode, int toNode, int connectionCost, bool compareByCost = false){
// take the provided stock information and insert it into the object
stringstream fromNodeSS;
fromNodeSS << fromNode;
this->fromNode = fromNodeSS.str();
stringstream toNodeSS;
toNodeSS << toNode;
this->toNode = toNodeSS.str();
this->connectionCost = connectionCost;

// set the comparator to our chosen comparision term
if (!compareByCost){
this->comparator = this->fromNode; // we use from node in this case, since we build the tree outwards
}
else{
stringstream ss;
ss << this->connectionCost;
this->comparator = ss.str(); // we use the connection cost in this case, to allow us to sort new connections
}

// set this as a non-null (active) record
this->nullRecord = false;
}

最佳答案

您的运营商实际上无效。

运营商<如果您希望它可用于排序,则必须具有许多数学属性。一个是 AntiSymmetry 属性:

x < y => !(y < x)

让我们定义x = "b"y = "aa" .

  • x < y因为 "b" 的长度不如"aa"的长度
  • y < x因为"aa"不如"b"

嗯?

另请注意,您对数字的定义很奇怪,因为它们的前缀为 0

哦,比较字符串比比较数字慢得多。

我的看法?停止更改具有比较信息的节点。实际比较模式与节点本身无关。

然后你就写两个比较方法,一个按成本比较,一个按原产地比较。


回到最初的问题,如何编写一个考虑 ["a", "b", "aa"] 的比较器排序了吗?

您快到了,但是“长度”比较不完整。只有在长度不同的情况下,您才需要回退到实际的词法比较,因此您忘记了右侧参数的长度低于左侧参数的情况。

因此,假设有两个字符串,正确的形式是:

bool compare(std::string const& lhs, std::string const& rhs) {
if (lhs.length() < rhs.length()) { return true; }
if (rhs.length() < lhs.length()) { return false; } // don't forget this
return lhs < rhs;
}

关于c++ - 在 C++ 中重载比较运算符导致 "invalid operator<",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5786296/

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