C++ &引用;越界迭代器“;空空如也
我在这段代码中遇到了一个分段错误:C++ &引用;越界迭代器“;空空如也,c++,iterator,segmentation-fault,set,c++17,C++,Iterator,Segmentation Fault,Set,C++17,我在这段代码中遇到了一个分段错误: #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()
#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;
}
}
这是未定义的行为:
std::set<int> st;
auto rf = --st.end();
std::set st;
自动射频=--st.end();
由于st
是空的,st.begin()==st.end()
和递减这两个(相同)迭代器中的任何一个都是格式错误的
我也用vector试过了,运行良好
这是UB最有害的后果之一:看起来似乎没问题。不是。这是未定义的行为:
std::set<int> st;
auto rf = --st.end();
std::set st;
自动射频=--st.end();
由于st
是空的,st.begin()==st.end()
和递减这两个(相同)迭代器中的任何一个都是格式错误的
我也用vector试过了,运行良好
这是UB最有害的后果之一:看起来似乎没问题。它不是。你不能做
--sr.end()空容器的代码>。我不管你是否去引用迭代器。您有未定义的行为,任何更改都可以在不作解释的情况下引发该行为。请使用调试器捕获崩溃。如果std::set
为空,则begin==end
为真,这意味着递减end
没有意义,而且有未定义行为的味道。伙计们,不要在注释中回答;)另一方面,如果您想要指向最后一个元素的东西,并且除了作为双向运算符之外不关心它的类型,那么您可以使用st.rbegin()
您不能执行--sr.end()空容器的代码>。我不管你是否去引用迭代器。您有未定义的行为,任何更改都可以在不作解释的情况下引发该行为。请使用调试器捕获崩溃。如果std::set
为空,则begin==end
为真,这意味着递减end
没有意义,而且有未定义行为的味道。伙计们,不要在注释中回答;)另一方面,如果您想要指向最后一个元素的东西,并且除了作为BidirectionalIterator
之外不关心它的类型,那么您可以使用st.rbegin()