【发布时间】:2011-08-12 18:41:57
【问题描述】:
目前正在尝试在 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;
}
【问题讨论】:
-
什么是比较器?发布代码。
-
你能说明比较器的定义吗?
-
@Mike 和 @Mario -- 比较器在 nodeRecord 对象的初始化期间被初始化。你可以在上面看到这个。
标签: c++ sorting operators operator-overloading overloading