std::vector函数_vector :: front(),vector :: back(),vector :: at()和vector :: data()函数,并带有示例| C ++ STL...

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中的向量元素访问。

  1. vector::front()

    向量:: front()

    Returns reference to the first element of a vector i.e. we can say it returns first element of the vector.

    返回对向量的第一个元素的引用,即可以说它返回向量的第一个元素。

  2. vector::back()

    向量:: back()

    Returns reference to the last element of a vector i.e. we can say it returns last element of the vector.

    返回对向量的最后一个元素的引用,即可以说它返回向量的最后一个元素。

  3. 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 元素。

  4. 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函数

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值