std::vector函数
vector::front(), vector::back(), vector::at() and vector::data() functions are the predefined function of vector class, which are used for vector element accessing in C++ STL.
vector :: front() , vector :: back() , vector :: at()和vector :: data()函数是vector类的预定义函数,用于C ++ STL中的向量元素访问。
vector::front()
向量:: front()
Returns reference to the first element of a vector i.e. we can say it returns first element of the vector.
返回对向量的第一个元素的引用,即可以说它返回向量的第一个元素。
vector::back()
向量:: back()
Returns reference to the last element of a vector i.e. we can say it returns last element of the vector.
返回对向量的最后一个元素的引用,即可以说它返回向量的最后一个元素。
vector::at(i)
向量:: at(i)
Returns reference to the
返回对
ith element of a vector i.e. we can say it returns ith element of the vector.
向量的第 i 个元素,即可以说它返回向量的第 i 个元素。
vector::data()
向量::: data()
As we know, vector is a dynamic array, and it can also be accessed like an array style.
众所周知,向量是一个动态数组,也可以像数组样式一样进行访问。
vector::data() returns the direct pointer to the first element of array (used by vector in the memory) and we can access all elements.
vector :: data()返回指向数组第一个元素的直接指针(由内存中的vector使用),我们可以访问所有元素。
Example:
例:
Input:
vector<int> num{10, 20, 30, 40, 50}
Output:
num.front(): 10
num.back(): 50
num.at(2): 30
All elements using vector::data(): 10 20 30 40 50
Program:
程序:
#include <iostream>
#include <vector>
using namespace std;
int main() {
//declare vector
vector<int> num{10, 20, 30, 40, 50};
//vector::front ()
cout<< "num.front(): " << num.front() <<endl;
//vector::back ()
cout<< "num.back() : " << num.back() <<endl;
//vector::at ()
cout<< "num.at(2) : " << num.at(2) <<endl;
//vector::data ()
int *ptr = num.data();
cout<< "All elements using vector::data () : ";
//note: there is no need to use vector iterator
for( int i =0; i<num.size(); i++)
cout<< *(ptr+i) << " ";
cout<<endl;
return 0;
}
Output
输出量
num.front(): 10
num.back() : 50
num.at(2) : 30
All elements using vector::data () : 10 20 30 40 50
翻译自: https://www.includehelp.com/stl/vector-front-back-at-and-data-functions-with-examples.aspx
std::vector函数