Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/152.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/fortran/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ &引用;越界迭代器“;空空如也_C++_Iterator_Segmentation Fault_Set_C++17 - Fatal编程技术网

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()