C++ Deque at() 使用方法及示例
C ++ Deque at()函数用于访问指定位置pos的元素。
注意:如果pos大于容器的大小,则该函数将引发异常,即“超出范围”。
语法
reference at(size_type pos);
参数
pos:它定义要返回的元素的位置。
其中,size_type是无符号整数类型。
返回值
它返回指定元素的引用。
实例1
让我们看一个简单的实例
#include <iostream> #include<deque> using namespace std; int main() { deque<char> ch={'n','h','o','o','o','.','c','o','m'}; for(int i=0;i<ch.size();i++) cout<<ch.at(i); return 0; }
输出:
(cainiaoplus.com)
实例2
让我们看一个简单的实例
#include <iostream> #include<deque> using namespace std; int main() { deque<int> k={1,2,3,4,5}; cout<<k.at(5); return 0; }
输出:
terminate called after throwing an instance of 'std::out_of_range'
在此示例中,at()函数尝试访问超出容器大小的元素。因此,它将引发异常,即超出范围。