Share via


vector<bool>::operator

Returns a simulated reference to the vector<bool> element at a specified position.

vector<bool>::reference operator[](
   size_type Pos
);
vector<bool>::const_reference operator[](
   size_type Pos
) const;

Parameters

Parameter

Description

Pos

The position of the vector<bool> element.

Return Value

A vector<bool>::reference or vector<bool>::const_reference object containing the value of the indexed element.

If the position specified is greater than or equal to the size of the container, the result is undefined.

Remarks

When compiling with _SECURE_SCL 1, a runtime error will occur if you attempt to access an element outside the bounds of the vector. See Checked Iterators for more information.

Example

This code example shows the correct use of vector<bool>::operator[] and two common coding mistakes (commented out of this code block). These are coding errors because you cannot take the address of the vector<bool>::reference object that vector<bool::operator[] returns.

// cl.exe /EHsc /nologo /W4 /MTd 
#include <vector>
#include <iostream>

int main()
{
    using namespace std;
    vector<bool> v;

    v.push_back(true);
    v.push_back(false);

//    bool* pvb = &v[1]; // conversion error - do not use
//    bool& vb = v[1];   // conversion error - do not use
    bool vb = v[1];
    cout << "The second element of v is " << ((vb) ? "true" : "false") << endl;
}

Output

The second element of v is false

Requirements

Header: <vector>

Namespace: std

See Also

Reference

vector<bool> Class

Standard Template Library