如果变量数据包含大于 vector 所有元素的整数,则仅在视觉工作室上接收"矢量下标超出范围"?

Recieving "vector subscript out of range" only on visual studio if variable data contains an integer greater than all elements of vector?

本文关键字:quot 工作室 范围 下标 视觉 vector 大于 变量 数据包 元素 整数      更新时间:2023-10-16
cin >> q;
while (q--)
{
cin >> data;
//if this value is greater than all the elements of the vector throwing error
vector<int>::iterator low = lower_bound(v.begin(), v.end(), data); //does the lower bound
if (v[low - v.begin()] == data)
cout << "Yes " << (low - v.begin() + 1) << endl;
else
cout << "No " << (low - v.begin() + 1) << endl;// while this should be the output
}

如果向量 V 包含 1 2 3 4 5 6 7 8 我们输入数据 9 然后它将错误显示为超出范围的矢量下标。

根据 cppreference.com 上的std::lower_bound()文档:

返回一个迭代器,指向范围[first, last)中的第一个元素,该元素不小于(即大于或等于(value如果未找到此类元素,则返回last

在你对lower_bound(v.begin(), v.end(), data)的调用中,当v{1 2 3 4 5 6 7 8}data是9时,v中没有>= data的元素,所以v.end()被返回到low。因此,low - v.begin()v.end() - v.begin(),它产生一个超出向量边界的索引 (8((有效索引为 0-7(。然后哪个Visual Studio警告你。

当找不到匹配的元素时,您需要添加std::lower_bound()条件检查:

auto low = lower_bound(v.begin(), v.end(), data);
if (low == v.end()) // <-- ADD THIS!
{
cout << "Not found" << endl;
}
else
{
auto index = low - v.begin();
if (v[index] == data)
cout << "Yes " << (index + 1) << endl;
else
cout << "No " << (index + 1) << endl;
}
仅在

视觉工作室上接收"矢量下标超出范围"...

Visual Studio给出这个断言是正确的。

Visual C++运行时的调试版本将检查std::vector的索引,并在存在越界访问时报告问题。

您使用的另一个编译器不会向您报告此错误,因为实际上,如果访问越界项,std::vectoroperator []具有未定义的行为。 因此,当你看到输出时,你就错了——你的程序有一个逐个错误。

为了证明这一点,下面是您的代码,但它使用at()而不是[ ]来访问元素:

#include <vector>
#include <iostream>
int main()
{
std::vector<int> v = {1,2,3,4,5,6,7,8};
std::vector<int>::iterator low = lower_bound(v.begin(), v.end(), 9); 
if (v.at(low - v.begin()) == 9)
std::cout << "Yes " << (low - v.begin() + 1) << std::endl;
else
std::cout << "No " << (low - v.begin() + 1) << std::endl;// while this should be the output
}

现场示例

注意到std::out_of_range例外吗? 现在,无论您使用哪种编译器,您都会收到相同的错误,因为vector::at()会进行边界检查。


现在这是您的原始代码:

原始代码

请注意,您获得输出,但您"静默"访问越界元素,因此程序的行为是未定义的。