C++98 中的异构容器查找

heterogeneous containers lookup in C++98

在我正在进行的项目中,我不得不使用 c++98。需要在某些结构向量中执行快速查找,仅使用这些结构的几个元素作为键,到目前为止,我很高兴地向 std::lower_boundstd::upper_bound 传递了一个 value 参数具有不同于那些结构的类型和可以正确处理这种异构情况的比较仿函数。

一切都按预期工作,但今天我突然意识到标准可能不允许这样做,并且我在几篇论文中找到了这种预感的证实,例如this one which also proposes an amendment to the standard which, I'm learning now, has been implemented in C++0x, as this other paper confirms

我的问题是:事实上我的代码是否按预期工作,尽管不遵守标准,只是巧合,具体实现的副作用,我应该更改编译器等等的非保证结果吗?

换句话说,考虑到这个代码库不会被编译,我真的应该真的真的改变我的代码以使其符合标准(这会使它变得非常复杂),还是我可以不去打扰它呢?暂时除了g++还有别的吗?

只有您可以决定保持现状是否值得冒险。但是,如果您移动到 ​​C++11,则措辞已更改以允许您正在做的事情。

我认为编译器供应商不太可能改变他们的标准库为旧版本标准工作的方式。因此,我看不出您的 C++98 代码很可能会中断,除非您将其移至未经测试的编译器。即使发生这种情况,您也可以始终实施自己的 std::lower_bound 版本(替代)来适应。

根据我对 C++11 标准的阅读,你很好。

25.4.3.1 lower_bound [ lower.bound ]

template<class ForwardIterator, class T>
ForwardIterator lower_bound(ForwardIterator first, ForwardIterator last, const T& value);

template<class ForwardIterator, class T, class Compare>
ForwardIterator lower_bound(ForwardIterator first, ForwardIterator last, const T& value, Compare comp);

1 Requires: The elements e of [first,last) shall be partitioned with respect to the expression e < value or comp(e, value).

2 Returns: The furthermost iterator i in the range [first,last] such that for any iterator j in the range [first,i) the following corresponding conditions hold: *j < value or comp(*j, value) != false.

3 Complexity: At most log 2 (last − f irst) + O(1) comparisons.

要求 2 并不规定 value*e.

属于同一类型

您引用的文档还说:

But is it legal? The standard's position on this question is not encouraging. For one thing, 25.3 says that for the algorithms to work correctly, the comparison object has to induce a strict weak ordering on the values.

这来自 C++03 标准并且 不是 我在 C++11 标准中找到的措辞:

25.4 Sorting and related operations [ alg.sorting ]

3 For all algorithms that take Compare, there is a version that uses operator< instead. That is, comp(*i, *j) != false defaults to *i < *j != false. For algorithms other than those described in 25.4.3 to work correctly, comp has to induce a strict weak ordering on the values.

它对std::lower_bound使用的算法进行了明确的豁免:

25.4.3 Binary search [ alg.binary.search ]

1 All of the algorithms in this section are versions of binary search and assume that the sequence being searched is partitioned with respect to an expression formed by binding the search key to an argument of the implied or explicit comparison function.

此措辞允许 "an argument" 比较函数与容器元素具有不同类型。它只需要匹配 "search key".