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