使用 equal_range 从多重映射搜索返回而不容易出错
我即将重构一些重复的代码。两个函数都使用以下方式在多重映射中进行搜索 equal_range()。在调用 equal_range() 之后的 for 循环中,有一个 for 循环设置 equalRange.first 的迭代器,条件为 it != equalRange.second。
如果找到正确的值,则两个函数会有所不同。我想做的是 将搜索功能作为以前使用的自己的帮助功能 提到了两个。
使其发挥作用不是问题。问题是我找不到办法 以对使用此代码的其他人有意义的方式使其变得“简单”并面向未来。 显然,我想要从搜索功能返回一些东西。
如果我要返回一个布尔值来指示是否在多重映射中找到该值,我会 必须将迭代器传递给指出元素的多重映射。我觉得相当 丑陋的。
如果返回的是迭代器,我们当然必须根据 边界回到使用搜索功能的两个函数中。我们无法检查 反对 multimap.end() 因为我们使用 equal_range 所以 equalRange.second 不必 等于 multimap.end()。
使用边界检查 returnIter == checkBound(x) 其中 checkBound(x) 返回 multimap::upperbound(x) 使 checkBound(x) 知道 equal_range 实现 的搜索功能。因此,如果其他人要改变搜索功能, checkBound(x) 可能无法按预期工作。
我在这里的立场是,搜索功能的用户不应该关心它是如何实现的,即不应该知道它使用 equal_range。
您对此有何意见和建议?我在这里说得太详细了吗?您将如何实现搜索功能?
谢谢
I'm about to refactor some duplicated code. Two functions both search in a multimap using
equal_range(). In a for loop after the call to equal_range() there is a for loop that sets
an iterator to equalRange.first with the condition it != equalRange.second.
If the correct value is found, the two functions differ. What I would like to do is
to have the search function as an own help function used by the previously
mentioned two.
Making that work is not the problem. What is the problem is that I cannot figure out a way
to make it "easy" and future proof in a way that makes sense to other people using this code.
Obviously, I would like something returned from the search function.
If I were to return a boolean to indicate if the value was found in the multimap, I would
have to pass an iterator to the multimap which points out the element. I find that quite
ugly.
If an iterator was returned instead, we of course have to check that against the
boundaries back in the two functions that use the search function. We can't check it
against multimap.end() since we use equal_range so equalRange.second doesnt have to
equal multimap.end().
Using boundary checking returnIter == checkBound(x) where checkBound(x) returns
multimap::upperbound(x) makes the checkBound(x) aware of the equal_range implementation
of the search function. Hence, if someone else were to change the search function,
the checkBound(x) might not work as expected.
My standing point here is that the users of the search function should not be concerned with how it is implemented, i.e., should not know that it uses equal_range.
What are your inputs and suggestions to this? Am I over-detailed here? How would you have implemented the search function?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在我看来,您不想做诸如
map::insert
之类的函数所做的事情 - 返回一个std::pair
表示搜索功能的位置和成功/失败。Instead of an either/or decision on the return value, it sounds to me like you'd want to do what functions like
map::insert
do - return astd::pair<iterator, bool>
to signal both the position and the success/failure of the search function.