C ++ Deque operator []函數(shù)用于訪(fǎng)問(wèn)指定位置pos的元素。如果位置pos大于容器的大小,則它將返回值0。
當(dāng)位置pos大于容器的大小時(shí),operator []()函數(shù)將返回值0,而at()函數(shù)將引發(fā)異常,即超出范圍。
reference operator[] (int pos);
pos:它定義要訪(fǎng)問(wèn)的元素的位置。
它返回對(duì)雙端隊(duì)列容器中位置pos處元素的引用。
讓我們看一個(gè)簡(jiǎn)單的實(shí)例
#include <iostream>
#include<deque>
using namespace std;
int main()
{
deque<string> a={"mango","is","my","favorite","fruit"};
for(int i=0;i<a.size();i++)
{
cout<<a.operator[](i);
cout<<" ";
}
return 0;
}輸出:
mango is my favorite fruit
在此示例中,operator []()函數(shù)訪(fǎng)問(wèn)雙端隊(duì)列a的每個(gè)元素。
讓我們看一個(gè)簡(jiǎn)單的示例,說(shuō)明pos超出范圍。
#include <iostream>
#include<deque>
using namespace std;
int main()
{
deque<int> a={1,2,3,4,5,6};
cout<<a.operator[](7);
return 0;
}輸出:
0
在此示例中,operator []()函數(shù)嘗試訪(fǎng)問(wèn)大于容器大小的位置。因此,它返回0。