gpt4 book ai didi

c++ - "Out of bound iterator"为空集

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:14:51 25 4
gpt4 key购买 nike

我在这段代码中遇到了段错误:

#include <iostream>
#include <set>

int main() {
std::set<int> st;
auto rf = --st.end();
std::cout << "Size of the set is: " << (int) st.size() << std::endl;

if ( (int) st.size() > 0) { // size of st is zero here
int foo = (*rf); // rf is out bound
std::cout << "foo: " << foo << std::endl;
}
}

由于 st 为空,if 条件永远不会为真,无论 rf 是否超出范围。如果我注释掉 if block ,那么程序运行正常。

我也用 std::vector 试过了,它运行良好。

为什么会出现段错误?为什么'always false if condition with invalid statement'会影响代码的运行?

编译:

g++ -Wall -Wextra -Wshadow -Wfloat-equal -pedantic -std=c++17 -Wconversion -lm test.cpp

最佳答案

这是未定义的行为:

std::set<int> st;
auto rf = --st.end();

因为 st 是空的,st.begin() == st.end() 并且递减这两个(和相同的)迭代器之一是错误的.

I have tried it with vector also and runs fine.

这是 UB 最有害的后果之一:它可能看起来还不错。它不是。

关于c++ - "Out of bound iterator"为空集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50913028/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com