BSc*_*ker 7 c++ sorting overloading operator-overloading operators
目前正在尝试使用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);
}
Run Code Online (Sandbox Code Playgroud)
此操作在运行时期间导致"Expression:invalid operator <"消息.
关于我犯错误的任何想法?似乎我应该能够准确地指示操作如何进行排序操作 - 即使它是无效的,因为我当前正在使用向量来包含对象.
初始化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;
}
Run Code Online (Sandbox Code Playgroud)
Mat*_* M. 10
您的运营商实际上无效.
<如果您希望运算符可用于排序,则必须具有许多数学属性.一个是AntiSymmetry属性:
x < y => !(y < x)
让我们来定义x = "b"和y = "aa".
x < y因为长度"b"不如长度"aa"y < x因为"aa"不如"b"哼
另请注意,如果数字以0s 为前缀,您的定义很奇怪.
哦,比较字符串比比较字符慢.
我的看法?停止使用比较信息更改节点.实际比较模式与节点本身无关.
然后你将只编写两种比较方法,一种是按成本进行比较,另一种是按来源进行比较.
并回到最初的问题,如何编写一个考虑["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;
}
Run Code Online (Sandbox Code Playgroud)