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

起因

最近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)的方式避免歧义。

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