back函数
语法:
1 2 |
reference back(); const_reference back() const; |
back() 返回最末一个元素
源代码
1 2 3 4 5 6 7 8 9 10 11 12 13 |
/** * Returns a read/write reference to the data at the last * element of the %vector. */ reference back() { return *(end() - 1); } /** * Returns a read-only (constant) reference to the data at the * last element of the %vector. */ const_reference back() const { return *(end() - 1); } |
测试代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
// 梁笔记 // https://zouzhongliang.com #include <iostream> #include <vector> using namespace std; int main() { vector<int> v1(5, 0); vector<int> v2(10, 2); v1.push_back(100); cout<<"v1最末元素是:"<< v1.back()<<endl; for(int i=0;i<v1.size();++i){ cout<<v1[i]<<endl; } } |
测试结果:
1 2 3 4 5 6 7 |
v1最末元素是:100 0 0 0 0 0 100 |