目前试图排序对象的矢量,其中每个对象包含字符串,在C++重载对比操作者在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;
}
有什么比较?发布代码。 – 2011-04-26 05:29:50
你能不能显示比较器的定义? – 2011-04-26 05:45:09
@Mike和@Mario - 比较器在初始化nodeRecord对象期间初始化。你可以看到上面的内容。 – BSchlinker 2011-04-26 05:50:31