Skip to main content

std::vector operator[]

// prism-push-types:reference,const_reference,size_type
// Non const version
constexpr reference operator[]( size_type pos );

// Const version
constexpr const_reference operator[]( size_type pos ) const;

Returns a reference

to the element at specified index pos.

caution

No bounds checking is performed.

Parameters

  • pos - position of the element to return

Return value

Reference to the requested element.

Exceptions

(none)

Complexity

Constant - O(1).

Example

Main.cpp
#include <vector>
#include <iostream>

int main()
{
std::vector<int> numbers {2, 4, 6, 8};

std::cout << "Second element: " << numbers[1] << '\n';

numbers[0] = 5;

std::cout << "All numbers:";
for (auto i : numbers) {
std::cout << ' ' << i;
}
std::cout << '\n';
}
Output
Second element: 4
All numbers: 5 4 6 8
This article originates from this CppReference page. It was likely altered for improvements or editors' preference. Click "Edit this page" to see all changes made to this document.
Hover to see the original license.

std::vector operator[]

// prism-push-types:reference,const_reference,size_type
// Non const version
constexpr reference operator[]( size_type pos );

// Const version
constexpr const_reference operator[]( size_type pos ) const;

Returns a reference

to the element at specified index pos.

caution

No bounds checking is performed.

Parameters

  • pos - position of the element to return

Return value

Reference to the requested element.

Exceptions

(none)

Complexity

Constant - O(1).

Example

Main.cpp
#include <vector>
#include <iostream>

int main()
{
std::vector<int> numbers {2, 4, 6, 8};

std::cout << "Second element: " << numbers[1] << '\n';

numbers[0] = 5;

std::cout << "All numbers:";
for (auto i : numbers) {
std::cout << ' ' << i;
}
std::cout << '\n';
}
Output
Second element: 4
All numbers: 5 4 6 8
This article originates from this CppReference page. It was likely altered for improvements or editors' preference. Click "Edit this page" to see all changes made to this document.
Hover to see the original license.