C++ vector::back() 函數
vector::back() 是 "vector" 頭文件的庫函數,用於訪問向量的最後一個元素,返回對向量最後一個元素的引用。
注意:要使用矢量,請包括<vector>
標題。
vector::back() 函數的語法
vector::back();
參數: none
——它什麽都不接受。
返回值: reference
– 它返回對向量最後一個元素的引用。
例:
Input: vector<int> vector1{ 1, 2, 3, 4, 5 }; Function call: cout << vector1.back() << endl; Output: 5
C++程序演示vector::back()函數的例子
//C++ STL program to demonstrate example of
//vector::back() function
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> v1{ 10, 20, 30, 40, 50 };
//accessing last element
//using vector::back() function
cout << "last element is:" << v1.back() << endl;
//changing last element
v1.at(v1.size() - 1) = 100;
cout << "now, last element is:" << v1.back() << endl;
//changing last element
//using push_back()
v1.push_back(200);
cout << "now, last element is:" << v1.back() << endl;
return 0;
}
輸出
last element is:50 now, last element is:100 now, last element is:200
參考:C++ vector::back()
相關用法
- C++ vector::begin()用法及代碼示例
- C++ vector::begin()、vector::end()用法及代碼示例
- C++ vector::max_size()用法及代碼示例
- C++ vector::rbegin()用法及代碼示例
- C++ vector::pop_back()用法及代碼示例
- C++ vector::crend()用法及代碼示例
- C++ vector::push_back()用法及代碼示例
- C++ vector::emplace_back用法及代碼示例
- C++ vector::at()用法及代碼示例
- C++ vector::swap()用法及代碼示例
- C++ vector::shrink_to_fit()用法及代碼示例
- C++ vector::cbegin()用法及代碼示例
- C++ vector::assign()用法及代碼示例
- C++ vector::cend()用法及代碼示例
- C++ vector::operator[]用法及代碼示例
- C++ vector::clear()用法及代碼示例
- C++ vector::cbegin()、vector::cend()用法及代碼示例
- C++ vector::empty()用法及代碼示例
- C++ vector::front()、vector::back()用法及代碼示例
- C++ vector::at()、vector::swap()用法及代碼示例
注:本文由純淨天空篩選整理自 vector::back() function with example in C++ STL。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。