首页 > 编程语言 > 详细

C++中vector末尾元素end()和back()

时间:2021-04-13 10:01:37      阅读:17      评论:0      收藏:0      [点我收藏+]

起因

最近code review看到有关vector末尾元素的问题

代码

一个简单的例子

#include <iostream>
#include <vector>
int main()
{
    std::vector<int> vec{1,2,3,4,5};
    std::cout<<*vec.end()<<std::endl;
    std::cout<<vec.back()<<std::endl;
    return 0;
}

输出结果

$ g++ ./test.cpp
$ ./a.out
114585
5

解释

官方文档的说法

end(): An iterator to the element past the end of the sequence.
back(): A reference to the last element in the vector.

end()返回末尾元素itor+1的结果,数值无法预料。
back()返回末尾元素的引用,可以正常修改。
日常使用for循环配合itor自增的方式,终止条件使用vec.end()自然也就无法发现问题。
对于元素的修改,更加推荐for (auto& i: vector)的方式避免歧义。

C++中vector末尾元素end()和back()

原文:https://www.cnblogs.com/azureology/p/14651233.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!