lower_bound 在函数中表现怪异,在 main() 中表现正常

lower_bound acts weirdly in the function and normally in the main()

我有这段代码:

        int main() {
            const vector<string> sorted_strings = { "zzzу", "zzzzу",
                                                    "zzzzzу", "zzzzzzzу" };
           cout << *lower_bound(begin(sorted_strings), 
                                end(sorted_strings), "zzzy");
        }

我希望 cout 打印 "zzzу",因为 lower_bound 应该打印等于或大于 val 参数的元素。

但是,当我 运行 在 main() 之外的函数中使用同一行代码时,事情变得很奇怪:

template <typename RandomIt>
pair<RandomIt, RandomIt> FindStartsWith(RandomIt range_begin, 
                                        RandomIt range_end, const string& prefix) {

    // Empty range
    if (range_begin == range_end)
        return { range_begin, range_begin };

    // When there is at least one word with the prefix
    RandomIt it_begin = lower_bound(range_begin, range_end, "zzzу");
    cout << (*it_begin) << endl;
    return {{}, {}};
}

    int main() {

    const vector<string> sorted_strings = { "zzzу", "zzzzу", 
                                            "zzzzzу", "zzzzzzzу" };
    cout << *lower_bound(begin(sorted_strings), end(sorted_strings), "zzzy") << endl;
    const auto mo_result = FindStartsWith(begin(sorted_strings), 
                           end(sorted_strings), "zzzу"); 
    return 0;
    }

我期望的main()FindStartsWith() 都打印 zzzу

我得到的:只有 main() 做到了。

您在上面源代码的字符串文字中有一些 non-printable 或宽字符。有趣的家伙。

(然后您试图取消引用 end() 处的迭代器,其行为未定义。)

函数中的字符串文字包含隐藏字符,因此没有匹配来自lower_bound

并且因为您在取消引用之前从未检查 lower_bound 的结果不是 range_end,所以您有未定义的行为。

函数应该使用 prefix,无论如何。