deque::operator[] and deque::at (STL Sample)

The sample code below illustrates how to use the deque::operator[] and deque::at STL function in Visual C++.

Required Header:
< deque>

Prototype:

   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;

Note: The class/parameter names in the prototype do not match the version in the header file. Some have been modified to improve readability.

Description:
The member function operator[] returns a reference to the element of the controlled sequence at position pos. If that position is invalid, the behavior is undefined. The member function at returns a reference to the element of the controlled sequence at position pos. If that position is invalid, the function throws an object of class out_of_range. The member function empty returns true for an empty controlled sequence.

Sample Code:

//////////////////////////////////////////////////////////////////////
//
// Compile options needed: -GX
//
// deque.cpp :
//
// Functions:
//
//    operator[]
//    at
//    empty
//    push_back
//    begin
//    end
//////////////////////////////////////////////////////////////////////

/* Compile options needed:-GX
*/
#include <iostream>
#include <deque>

using namespace std;


typedef deque<char >  CHARDEQUE;
void print_contents (CHARDEQUE  deque, char*);

void 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;
}

 

Program Output is:

a is empty
a is not empty
The contents of a : A B C D
The first element of a is  A
The first element of a is  A
The last element of a is  D
The last element of a is  D