lower_bound()返回最后一个元素

lower_bound() return the last element

本文关键字:返回 最后一个 元素 bound lower      更新时间:2023-10-16

当我解决392.Is Subsequence的问题时。Leetcode上。

当我使用lower_bound()的函数时,我无法理解我想找到最后一个元素和它没有找到然后返回最后一个元件之间的区别。

这是我的代码:

class Solution {
public:
bool isSubsequence(string s, string t) {
vector<vector<int>> temp(26);
for (int i = 0; i < t.length(); ++i)
temp[t[i]-'a'].push_back(i);
int index = -1;
for (int i = 0; i < s.length(); ++i) {
auto it = upper_bound(temp[s[i]-'a'].begin(), temp[s[i]-'a'].end(), index);
//if the last element is we want to find what will happen?
if (it == temp[s[i]-'a'].end()) return false;
index = *it;
}
return true;
}
};

如果最后一个元素是我们想知道会发生什么?

end()不指向最后一个元素,而是指向最后元素之外的。重点矿:

在给定容器c或数组的末尾(即最后一个元素之后的元素(返回迭代器。

如果最后一个元素是您想要查找的,lower_bound将返回end() - 1