vector::front() and vector::back() in C++ STL

C++中的vector是一个动态数组,支持自动调整大小。vector::front()用于获取vector的第一个元素,如果为空则产生未定义行为;vector::back()用于获取vector的最后一个元素,同样在为空时产生未定义行为。这两个函数在非空vector上运行时不会抛出异常。front()和back()返回元素的引用,而begin()和end()返回指向元素的迭代器。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Vectors are same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container.

vector::front()

This function can be used to fetch the first element of a vector container.获得vector的第一个元素

Syntax :

vectorname.front()
Parameters :
No value is needed to pass as the parameter.
Returns :
Direct reference to the first element of the vector container.

Examples:

Input  :  myvector = 1, 2, 3
          myvector.front();
Output :  1

Input  :  myvector = 3, 4, 1, 7, 3
          myvector.front();
Output :  3

Errors and Exceptions

1. If the vector container is empty, it causes undefined behaviour. 如果vector为空,导致未定义行为
2. It has a no exception throw guarantee if the vector is not empty. 

// CPP program to illustrate 
// Implementation of front() function 
#include <iostream> 
#include <vector> 
using namespace std; 

int main() 
{ 
	vector<int> myvector; 
	myvector.push_back(3); 
	myvector.push_back(4); 
	myvector.push_back(1); 
	myvector.push_back(7); 
	myvector.push_back(3); 
	// Ve
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值