取消引用字符串向量的.end()时的行为 [英] Behavior when dereferencing the .end() of a vector of strings

查看:86
本文介绍了取消引用字符串向量的.end()时的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道设置字符串是否等于通过取消引用端部 iterator 字符串向量。当我运行程序

I'm wondering if it's "safe" to set a string equal to whatever is returned by dereferencing the off-the-end iterator of a vector of strings. When I run the program

#include <vector>
#include <string>

int main()
{

    std::vector<std::string> myVec;
    std::cout << *myVec.end();
    return 0;
}

我收到以下错误。

/usr/local/lib/gcc/i686-pc-linux-gnu/4.1.2/../../../../include/c++/4.1.2/debug/safe_iterator.h:181:
    error: attempt to dereference a past-the-end iterator.

Objects involved in the operation:
iterator "this" @ 0x0xffdb6088 {
type = N11__gnu_debug14_Safe_iteratorIN9__gnu_cxx17__normal_iteratorIPSsN10__gnu_norm6vectorISsSaISsEEEEEN15__gnu_debug_def6vectorISsS6_EEEE (mutable iterator);
  state = past-the-end;
  references sequence with type `N15__gnu_debug_def6vectorISsSaISsEEE' @ 0x0xffdb6088
}

Disallowed system call: SYS_kill

您可以在 http://codepad.org/fJA2yM30

我想知道所有这些的原因是因为我的代码中有一个片段,就像

The reason I'm wondering about all this is because I have a snippet in my code that is like

std::vector<const std::string>::iterator iter(substrings.begin()), offend(substrings.end());
while (true)
{
    this_string = *iter;
    if (_programParams.count(this_string) > 0)
    {
        this_string = *++iter;

我想确保如果 ++不会发生奇怪的事情iter 等于违规

推荐答案

您说过:


我想知道它是否安全?通过取消引用字符串向量的端部迭代器来设置等于返回值的字符串

I'm wondering if it's "safe" to set a string equal to whatever is returned by dereferencing the off-the-end iterator of a vector of strings

不,这是不安全的。来自 http://en.cppreference.com/w/cpp/container/vector/ end

No, it is not safe. From http://en.cppreference.com/w/cpp/container/vector/end


将迭代器返回到容器最后一个元素之后的元素。

Returns an iterator to the element following the last element of the container.

此元素充当占位符;尝试访问它会导致未定义的行为。

This element acts as a placeholder; attempting to access it results in undefined behavior.

这篇关于取消引用字符串向量的.end()时的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆