开发者

Returning from a multimap search with equal_range without being error-prone

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 eq开发者_如何学Cual 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


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 a std::pair<iterator, bool> to signal both the position and the success/failure of the search function.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜