c++ - 为什么取消引用迭代器会切断输出流?

标签 c++ iterator cout deque

我在练习 std::deque ,特别是迭代器

我测试了 end迭代器。像这样:

    std::deque<const char*> wup {"how","are","you","doing","today?"};
    std::deque<const char*>::iterator it = wup.end();

然后,我要打印it ,并且我知道结束迭代器是空的。

enter image description here

然后我尝试使用 2 cout语句打印it的内容: 其中之一之前 --it另一个在 --it 之后

但是如果我写一个 cout之前 --it , 最后一个cout不会出现在输出中。

是这样的:

std::deque<const char*> wup {"how","are","you","doing","today?"};
std::deque<const char*>::iterator it = wup.end();
std::cout<<"Before --it: "<<*it<<std::endl;// okay, it works good | and finishes console
--it;
std::cout<<"After --it: "<<*it<<std::endl;// I do not know why it does not appear.

输出:

    Before --it:
    Process returned 0 (0x0)   execution time : 0.010 s
    Press ENTER to continue.

我哪里弄错了?
如果取消引用迭代器是错误的...
为什么在这种情况下,毫无异常(exception)地切断输出流
多谢。 测试于:
OS: Ubuntu 16.01
compiler: g++ version: 5.3.1
IDE: code::blocks 16.01


编辑: 我在/reference/en/cpp/container/map/erase.html 中找到了这个note:

迭代器 pos 必须有效且可取消引用。因此 end() 迭代器(有效,但不是可解引用)不能用作 pos 的值。

I think this is real reason for, why ... .

我的母语不是英语,所以如果你看到一些错误,请原谅

最佳答案

Where did i make a mistake?

这一行:

std::cout<<"Before --it: "<<*it<<std::endl;

取消引用指向容器末尾的迭代器,这是未定义的行为。

Why this case, cuts the output-stream without any exception?

这个问题分为两部分:

  1. 为什么它会切断输出流?因为未定义的行为是未定义的。你不知道会发生什么。有很多关于此的信息:http://en.cppreference.com/w/cpp/language/ub

  2. 为什么没有异常(exception)?为了对所有可能导致 UB 的情况提供异常,c++ 必须检查每个取消引用,这在计算上会很昂贵,但 yield 很小。是否正确使用迭代器接口(interface)取决于用户。这在以下示例中是相同的:


 int a[5];
 a[6] = 10; // Why does c++ allow this when it is clearly a mistake? Because the user is 
            // responsible for writing good code, not the compiler, and certainly
            // not the run-time exception handler.  

关于c++ - 为什么取消引用迭代器会切断输出流?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38083028/

相关文章:

c++ - std::map::iterator 是否返回值的拷贝或值本身?

c++ - 将迭代器传递给模板

java - 如何迭代泛型的 HashMap ?

c++ - 重载 << 运算符和递归

C++整行在不应该的时候被着色

c++ - 非阻塞读取文件/获取文件描述符c++

c++ - 以下排序算法是否为O(n)?

c++ - 为什么我的字符串的开头消失了?

c++ - 从 C 到 C++ 并返回

c++ - Qt 应用程序和 Google Breakpad