大佬教程收集整理的这篇文章主要介绍了在C中重载比较运算符导致“无效运算符<”,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
字符串可以包含字母或数字(由于设计约束,这是必要的,因为比较器可以更改).
此时,对象的类被重载,因此当比较两个对象时,将比较它们包含的字符串.这是有用的 – 然而,当我使用排序操作(例如STL排序)按顺序放置对象时,它将按顺序排序三个字符串,如“1”,“4”,“12” “1”,“12”,“4”. 4大于12,但因为它从最左边的数字开始比较,所以发生这种“不正确”排序.
我最初的反应是改变比较操作的重载方式.我首先检查我正在比较的字符串的长度 – 如果字符串的内容大或小,这将是一个明显的标志.
// 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); }
此操作导致“表达式:无效运算符<”运行时的消息. 关于我犯错误的任何想法?似乎我应该能够准确地指示操作如何进行排序操作 – 即使它是无效的,因为我当前正在使用向量来包含对象. 初始化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 =“b”和y =“aa”.
> x<因为“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中重载比较运算符导致“无效运算符<”所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。