我创建了一个地图ClassExpression作为键和std::string值.关键比较器如下
class ClassExpressionComparator {
public:
bool operator()(const ClassExpression& lhs,
const ClassExpression& rhs) const {
return ((lhs.quantifier == rhs.quantifier) &&
(lhs.property.compare(rhs.property) == 0) &&
(lhs.concept.compare(rhs.concept) == 0));
}
};
Run Code Online (Sandbox Code Playgroud)
ClassExpression包含比较器中提到的3个字段.我比较了所有3个领域.当我使用map的find()时,即使地图中没有键,它也会说它找到了键并给出了一个现有的键作为结果(获得第一个键作为结果).
我尝试了以下内容
boost::shared_ptr< std::map<ClassExpression, std::string,
ClassExpressionComparator> > cemap(
new std::map<ClassExpression,
std::string, ClassExpressionComparator>());
ClassExpression ce1;
ce1.quantifier = com::xxxx::kb::SOME;
ce1.property = "<http://www.w3.org/2002/07/acts-on>";
ce1.concept = "<http://www.w3.org/2002/07/Tissue>";
populateMap(cemap, ce1);
ClassExpression ce2;
ce2.quantifier = com::xxxx::kb::SOME;
ce2.property = "<http://www.w3.org/2002/07/contained-in>";
ce2.concept = "<http://www.w3.org/2002/07/HeartValve>";
populateMap(cemap, ce2);
ClassExpression ce3;
ce3.quantifier = com::xxxx::kb::SOME;
ce3.property = "<http://www.w3.org/2002/07/has-location>";
ce3.concept = "<http://www.w3.org/2002/07/Endocardium>";
std::map<ClassExpression, std::string, ClassExpressionComparator>::iterator
ceIterator = cemap->find(ce3);
if (ceIterator == cemap->end()) {
std::cout << "Not found" << std::endl;
}
else {
std::cout << "Found; concept = " << ceIterator->second << std::endl;
}
ClassExpressionComparator cmp;
std::cout << "compare: " << cmp(ce1, ce3) << std::endl;
Run Code Online (Sandbox Code Playgroud)
populateMap()只是做一个插入,在我的实际代码中,我做了一些更多的事情,我想保持相同的流程,所以就这样离开了.输出cmp(ce1, ce3)为0但是当我执行a时find(ce3),结果是它在第一个键位置找到它而不是返回end().我在哪里错了?
谢谢.
Raghava.
你写了一个平等比较.map需要一个小于比较.(或者如果您希望按键递减顺序,则大于.)
我通常这样做的习语:
bool operator()(const ClassExpression& lhs,
const ClassExpression& rhs) const {
return lhs.quantifier < rhs.quantifier? true
: rhs.quantifier < lhs.quantifier? false
: lhs.property.compare(rhs.property) < 0? true
: lhs.property.compare(rhs.property) > 0? false
: lhs.concept.compare(rhs.concept) < 0;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2647 次 |
| 最近记录: |