解引用向量的结束迭代器时打印的奇数值 [英] Odd values printed when dereferencing the end iterator of a vector

查看:56
本文介绍了解引用向量的结束迭代器时打印的奇数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个存储{1,2,3,4,5}的向量.我试图打印*(vec.end())并返回结果6.我不知道如何解释这一点.同样,调用vec.find(500)会得到结果6.为什么我得到这个数字?

I have a vector storing {1,2,3,4,5}. I tried to print *(vec.end()) and got back the result 6. I don't know how to explain this. Similarly, calling vec.find(500) gave the result 6. Why am I getting this number?

#include<iostream>
#include<iterator>
#include<set>
#include<map>
int main()
{
    int a[] = {1,2,3,4,5};
    std::set<int> set1(a,a+sizeof(a)/sizeof(int));
    for (std::set<int>::iterator itr=set1.begin();itr!=set1.end();++itr){
        std::cout << *itr << std::endl;
    }
    //std::pair<std::set<int>::iterator, bool> ret;
    //ret = set1.insert(1);
    //std::cout << *(ret.first) << "first;second" << ret.second << std::endl;
    std::set<int>::iterator itr1 = set1.begin();
    set1.insert(itr1,100);
    std::advance(itr1,3);
    std::cout << *itr1 << std::endl;
    std::cout << *(set1.find(500)) << std::endl;
    std::cout << *(set1.end()) << std::endl;
}

推荐答案

vec.end()并不指向最后一个元素,而是在最后一个元素的后面".

vec.end() does not point to the last element, but somewhat "behind" the last one.

您没有访问向量中的最后一个元素.相反,您要取消引用无效"迭代器,这是未定义的行为,在这种情况下,结果是向量中的无效索引.

You are not accessing the last element in the vector. Instead you are dereferencing an "invalid" iterator, which is undefined behaviour and turns out to be an invalid index in the vector in this case.

vec.find如果找不到搜索到的元素,则返回结束迭代器.

vec.find returns the end iterator if the searched element can not be found.

这篇关于解引用向量的结束迭代器时打印的奇数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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