Among all 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 to **return the element at a specified position** without performing bounds checking. Its usage is completely consistent with ordinary arrays. `operator[]` provides array-style random access capability, allowing you to quickly access elements at any position. Vocabulary: `operator[]` is the subscript operator; the square brackets are the symbol for 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
- Parameter:
pos- Type:
size_type(unsigned integer type, usuallysize_t) - Description: The position (index) of the element to access. Indexing starts from 0; the maximum valid index is
size() - 1.
- Type:
- Return Value: Returns a reference to the element at the specified position. If the container is a const container, returns a const reference.
- Effect: Returns the element at the specified position. No bounds checking is performed; out-of-bounds access results in 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.
## Examples Let's thoroughly master the usage of `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 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 : "<< numbers<< std::endl; std::cout<<"Second element : "<< numbers<< std::endl; std::cout<<"Third element : "<< numbers<< std::endl; std::cout<<"Last element : "<< numbers<< 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<<" "; } std::cout<< std::endl; return 0; } Expected Output: Vector size is: 5First element : 10Second element : 20Third element : 30Last element : 50All elements: 10 20 30 40 50 Code Analysis:
numbersreturns the first element10(indexing starts from 0).numbersreturns the last element50(becausesize()is 5, valid indices are 0-4).- Using a loop with
operator[]can traverse all elements; the usage is exactly the same as with arrays.
numbers = 100;modifies the first element's value through a reference.- This demonstrates that
operator[]returns a modifiable lvalue reference.
auto keyword, operator[] can be used more conveniently.
## Example
#include
#include
#include
int main(){
std::vector names ={"Alice", "Bob", "Charlie"};
// Use auto for automatic type deduction
for(size_t i =0; i < names.size();++i){
auto& name = names;// Deduced as std::string&
std::cout<<"Person "<<(i +1)<<": "<< name << std::endl;
}
return 0;
}
Expected Output:
Person 1: AlicePerson 2: BobPerson 3: Charlie
Code Analysis:
auto& name = names;is automatically deduced asstd::string&, allowing direct modification of elements.
operator[] and at().
## Example
#include
#include
#include
int main(){
std::vector numbers ={10, 20, 30};
// operator[] does not perform bounds checking; out-of-bounds access is at your own risk
// Here accessing numbers, but size() is 3, which 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<< std::endl;
}
std::cout<<"n at() 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<<"n Recommendation: Use operator[] when the index is guaranteed not to be out of bounds,"<< std::endl;
std::cout<<" use at() when uncertain to get exception protection."<< std::endl;
return 0;
}
Code Analysis:
operator[]is faster because it does not perform bounds checking.at()is safer but has the overhead of exception handling.- Selection advice: If the index is guaranteed safe (e.g., loop variable between 0 and size()-1), use
operator[]; if the index comes from external input or may be uncertain, useat().
operator[] to implement vector operations.
## Example
#include
#include
// Calculate the dot product of two vectors
int dotProduct(const std::vector& v1, const std::vector& v2){
int result =0;
for(size_t i =0; i < v1.size();++i){
result += v1* v2;
}
return result;
}
int main(){
std::vector v1 ={1, 2, 3};
std::vector 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<<" ";
}
std::cout<< std::endl;
std::cout<<"Vector v2: ";
for(size_t i =0; i < v2.size();++i){
std::cout<< v2<<" ";
}
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:
Vector v1: 1 2 3Vector v2: 4 5 6Dot product: 32
Code Analysis:
- Using
operator[]allows quick access to vector elements in algorithms. - The dot product calculation is the sum of products of corresponding position elements.
<img alt="Image 2: C++ Container Class " /> C++ Container Class
YouTip