C++ operator[] operator
Among all the ways to access vector elements,operator[] is the most commonly used and most direct one, just like accessing array elements.
operator[] is the subscript operator of the container class, used toreturn the element at the specified position, but does not perform bounds checking. Its usage is exactly the same as a normal array.
operator[] provides array-style random access, allowing you to quickly access elements at any position.
Word meaning: operator[] is the subscript operator; the square brackets are the symbol of array access.
Basic syntax and parameters
operator[] is a member function of the container class; just use it like an array.
Syntax format
reference operator[](size_type pos);
const_reference operator[](size_type pos) const;
Parameter Description
- Parameters:
pos - Type:
size_type(unsigned integer type, usuallysize_t) - Description: The position (index) of the element to access. Indexing starts at 0, and the maximum valid index is
size() - 1.
Function description
- Return Value: Returns areferenceto the element at the specified position. If the container is const, a const reference is returned.
- effect: Returns the element at the specified position. Does not perform bounds checking; out-of-bounds access has undefined behavior.
- Difference from at():
operator[]does not perform bounds checking and is slightly faster;at()performs bounds checking and throws an exception when out of bounds.
Example
Let us thoroughly master operator[] through a series of examples from simple to complex.
Example 1: Basic usage - accessing elements
Example
#include
#include
int
main
(
)
{
// 1. Create a vector and add some elements
std
::
vector
<
int
numbers
=
{
10
,
20
,
30
,
40
,
50
};
std
::
cout
<<
"vector size is: "
<<
numbers.
size
(
)
<<
std
::
endl
;
// 2. Use operator[] to access elements
std
::
cout
<<
"First element [0]: "
<<
numbers
[
0
]
<<
std
::
endl
;
std
::
cout
<<
"Second element [1]: "
<<
numbers
[
1
]
<<
std
::
endl
;
std
::
cout
<<
"Third element [2]: "
<<
numbers
[
2
]
<<
std
::
endl
;
std
::
cout
<<
"Last element [4]: "
<<
numbers
[
4
]
<<
std
::
endl
;
// 3. Use a loop to access all elements
std
::
cout
<<
"All elements: "
;
for
(
size_t
i
=
0
;
i
<
numbers.
size
(
)
;
++
i
)
{
std
::
cout
<<
numbers
[
i
]
<<
" "
;
}
std
::
cout
<<
std
::
endl
;
return
0
;
}
Expected output:
vector的大小是: 5
第一个元素 [0]: 10
第二个元素 [1]: 20
第三个元素 [2]: 30
最后一个元素 [4]: 50
所有元素: 10 20 30 40 50
Code analysis:
numbers[0]returns the first element10(indexing starts at 0).numbers[4]returns the last element50(becausesize()is 5, and the valid indices are 0-4).- Using a loop and
operator[]can traverse all elements; its usage is exactly the same as an array.
Example 2: Modifying element values
operator[] returns a reference, so it can be used to modify the element's value.
Example
#include
#include
int
main
(
)
{
std
::
vector
<
int
numbers
=
{
10
,
20
,
30
};
std
::
cout
<<
"Before modification: "
;
for
(
size_t
i
=
0
;
i
<
numbers.
size
(
)
;
++
i
)
{
std
::
cout
<<
numbers
[
i
]
<<
" "
;
}
std
::
cout
<<
std
::
endl
;
// Use operator[] to get a reference and modify the element
numbers
[
0
]
=
100
;
numbers
[
1
]
=
200
;
numbers
[
2
]
=
300
;
std
::
cout
<<
"After modification: "
;
for
(
size_t
i
=
0
;
i
<
numbers.
size
(
)
;
++
i
)
{
std
::
cout
<<
numbers
[
i
]
<<
" "
;
}
std
::
cout
<<
std
::
endl
;
return
0
;
}
Expected output:
修改前: 10 20 30
修改后: 100 200 300
Code analysis:
numbers[0] = 100;modified the value of the first element through the reference.- This demonstrates that
operator[]returns a modifiable lvalue reference.
Example 3: Use auto for automatic type deduction
combined with auto keyword, makes it more convenient to use operator[].
Example
#include
#include
#include
int
main
(
)
{
std
::
vector
<
std
::
string
names
=
{
"Alice"
,
"Bob"
,
"Charlie"
}
;
// Use auto for automatic type deduction
for
(
size_t
i
=
0
;
i
<
names.
size
(
)
;
++
i
)
{
auto
&
name
=
names
[
i
]
;
// Deduced as std::string&
std
::
cout
<<
"Round "
<<
(
i
1
)
<<
" person: "
<<
name
<<
std
::
endl
;
}
return
0
;
}
Expected output:
第 1 个人: Alice
第 2 个人: Bob
第 3 个人: Charlie
Code analysis:
auto& name = names[i]; is automatically deduced as std::string&, which can directly modify the element.Example 4: The difference between operator[] and at()
compares operator[] and at() 's behavioral differences.
Example
#include
#include
#include
int
main
(
)
{
std
::
vector
<
int
numbers
=
{
10
,
20
,
30
};
// operator[] does not perform bounds checking; out-of-bounds access is at your own risk
// Here we access numbers[5], but size() is 3; this is undefined behavior
// For demonstration, we only access the valid range
std
::
cout
<<
"operator[] access:"
<<
std
::
endl
;
for
(
size_t
i
=
0
;
i
<
3
;
++
i
)
{
std
::
cout
<<
"numbers["
<<
i
<<
"] = "
<<
numbers
[
i
]
<<
std
::
endl
;
}
std
::
cout
<<
"\nat() access (with bounds checking):"
<<
std
::
endl
;
for
(
size_t
i
=
0
;
i
<
3
;
++
i
)
{
std
::
cout
<<
"numbers.at("
<<
i
<<
") = "
<<
numbers.
at
(
i
)
<<
std
::
endl
;
}
std
::
cout
<<
"\nSuggestion: use operator[] when you are sure the index will not go out of bounds,"
<<
std
::
endl
;
std
::
cout
<<
" use at() when unsure to get exception protection."
<<
std
::
endl
;
return
0
;
}
Code analysis:
operator[]accesses faster because it does not perform bounds checking.at()is safer, but has the overhead of exception handling.- Selection suggestion: if the index is definitely safe (e.g., a loop variable between 0 and size()-1), use
operator[]; if the index comes from external input or may be uncertain, useat().
Example 5: Compute the vector dot product
Use operator[] implements vector operations.
Example
#include
#include
// Compute the dot product of two vectors
int
dotProduct
(
const
std
::
vector
<
int
&
v1,
const
std::
vector
<
int
&
v2
)
{
int
result
=
0;
for
(
size_t
i
=
0
;
i
<
v1.
size
(
)
;
++
i
)
{
result
=
v1
[
i
]
v2
[
i
]
;
}
return
result
;
}
int
main
(
)
{
std
::
vector
<
int
v1
=
{
1
,
2
,
3
};
std
::
vector
<
int
v2
=
{
4
,
5
,
6
};
int
result
=
dotProduct
(
v1, v2
)
;
std
::
cout
<<
"Vector v1: "
;
for
(
size_t
i
=
0
;
i
<
v1.
size
(
)
;
++
i
)
{
std
::
cout
<<
v1
[
i
]
<<
" "
;
}
std
::
cout
<<
std
::
endl
;
std
::
cout
<<
"Vector v2: "
;
for
(
size_t
i
=
0
;
i
<
v2.
size
(
)
;
++
i
)
{
std
::
cout
<<
v2
[
i
]
<<
" "
;
}
std
::
cout
<<
std
::
endl
;
std
::
cout
<<
"Dot product: "
<<
result
<<
std
::
endl
;
// 14 + 25 + 3*6 = 4 + 10 + 18 = 32
return
0
;
}
Expected output:
向量 v1: 1 2 3
向量 v2: 4 5 6
点积: 32
Code analysis:
- Use
operator[]can quickly access vector elements in algorithms. - The dot product is computed by multiplying corresponding elements and then summing them.
The C++ container class