deque::operator[] 和 deque::at
說明如何使用 deque::operator [ 和 deque::at Visual C++ 標準樣板程式庫 (STL) 函式。
const_reference operator[](
size_type Pos
) const;
reference operator[](
size_type Pos
);
const_reference operator[](
difference_type _N
) const;
reference operator[](
difference_type _N
) const;
const_reference at(
size_type Pos
) const;
reference at(
size_type Pos
); bool empty( ) const;
備註
![]() |
---|
在原型中的類別/參數名稱不相符的標頭檔中的版本。某些已修改以提高可讀性。 |
運算子 [成員函式會傳回位置受控制序列的項目之參考 Pos。 如果該位置不正確的是未定義的行為。 在 成員函式會傳回位置受控制序列的項目之參考 Pos。 如果該位置不正確,函式會擲回的物件類別的out_of_range。 空 成員函式會傳回 ,則為 true 為空的受控制序列。
範例
// operator.cpp
// compile with: /EHsc
//
// Functions:
// operator[]
// at
// empty
// push_back
// begin
// end
#include <iostream>
#include <deque>
using namespace std;
typedef deque<char > CHARDEQUE;
void print_contents (CHARDEQUE deque, char*);
int main()
{
//create an empty deque a
CHARDEQUE a;
//check whether it is empty
if(a.empty())
cout<<"a is empty"<<endl;
else
cout<<"a is not empty"<<endl;
//inset A, B, C and D to a
a.push_back('A');
a.push_back('B');
a.push_back('C');
a.push_back('D');
//check again whether a is empty
if(a.empty())
cout<<"a is empty"<<endl;
else
cout<<"a is not empty"<<endl;
//print out the contents
print_contents (a,"a");
cout <<"The first element of a is " <<a[0] <<endl;
cout <<"The first element of a is " <<a.at(0) <<endl;
cout <<"The last element of a is " <<a[a.size()-1] <<endl;
cout <<"The last element of a is " <<a.at(a.size()-1) <<endl;
}
//function to print the contents of deque
void print_contents (CHARDEQUE deque, char *name)
{
CHARDEQUE::iterator pdeque;
cout <<"The contents of "<< name <<" :";
for(pdeque = deque.begin();
pdeque != deque.end();
pdeque++)
{
cout <<" " << *pdeque;
}
cout<<endl;
}
需求
標頭: < deque >