C++ <vector> operator[] operator
Among all the ways to access vector elements,operator[]is the most common and direct one, just like accessing array elements.
operator[]is the subscript operator of container classes, used toreturn the element at the specified position, but it does not perform bounds checking. Its usage is exactly the same as that of a regular array.
operator[]provides array-style random access capability, allowing you to quickly access elements at any position.
Word Definitions: operator[]is the subscript operator, and the brackets are the symbol of array access.
Basic syntax and parameters
operator[]is a member function of the container class. Just use it as you would an array.
Syntax format
reference operator[](size_type pos); const_reference operator[](size_type pos) const;
Parameter description
- Parameter:
pos- Type:
size_type(an unsigned integer type, usuallysize_t) - Description: The position (index) of the element to be accessed. The index starts from 0, and the maximum valid index is
size() - 1。
- Type:
Function description
- Return Value: returns the ... of the element at the specified positionReference. If the container is a constant container, a constant reference is returned.
- Effect: returns the element at the specified position. No bounds checking is performed; accessing out of bounds results in undefined behavior.
- Difference from at():
operator[]Does not perform bounds checking, so it is slightly faster;at()performs bounds checking and throws an exception when out of bounds.
Example
Let us thoroughly master it through a series of examples ranging from simple to complex.operator[]Usage.
Example 1: Basic usage - accessing elements
Example
#include <vector>
int main() {
// 1. Create a vector and add some elements
std::vector<int> numbers = {10, 20, 30, 40, 50};
std::cout << "The size of the vector 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]Return the first element10(indices start from 0).numbers[4]returns the last element50(becausesize()is 5, and the valid indices are 0-4).- using loops and
operator[]can traverse all elements, and its usage is exactly the same as that of an array.
Example 2: Modifying element values
operator[]returns a reference, so it can be used to modify the value of an element.
Example
#include <vector>
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 elements
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;The value of the first element was modified through the reference.- This demonstrates
operator[]returns a modifiable lvalue reference.
Example 3: Using auto to deduce the type automatically
Combinationautokeyword, for more convenient useoperator[]。
Example
#include <vector>
#include <string>
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) << " people: " << name << std::endl;
}
return 0;
}
Expected output:
第 1 个人: Alice 第 2 个人: Bob 第 3 个人: Charlie
Code analysis:
auto& name = names[i];Automatically deduced asstd::string&, allowing direct modification of the element.Example 4: Difference between operator[] and at()
Comparisonoperator[]andat()Behavioral differences.
Example
#include <vector>
#include <stdexcept>
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 accessing numbers[5], but size() is 3, this is undefined behavior
// For demonstration, we only access 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 uncertain to get exception protection." << std::endl;
return 0;
}
Code analysis:
operator[]Access is faster because no bounds checking is performed.at()Safer, but with exception handling overhead.- Selection advice: If the index is certain to be safe (such as a loop variable between 0 and size()-1), use
operator[]; if the index comes from external input or may be uncertain, useat()。
Example 5: Calculating vector dot product
Usageoperator[]Implement vector operations.
Example
#include <vector>
// Calculate 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;
// 1*4 + 2*5 + 3*6 = 4 + 10 + 18 = 32
return 0;
}
Expected output:
向量 v1: 1 2 3 向量 v2: 4 5 6 点积: 32
Code analysis:
- Usage
operator[]can quickly access vector elements in algorithms. - The dot product is calculated by multiplying the elements at corresponding positions and then summing them.
other extensions