目前尝试在C++中对包含字符串的对象向量进行排序。
由于设计限制,这些字符串可能包含字母或数字(这是必要的,因为比较器可以更改)。
目前,对象的类已经过载,因此当比较两个对象时,它们包含的字符串会进行比较。这在一定程度上有效-然而,当我使用排序操作(例如STL sort)将对象排序时,它会将三个字符串排序为“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;
}