YouTip LogoYouTip

Cpp Libs Array Operator

[![Image 1: C++ Container Class ](#) C++ Container Class ](#) * * * Among all ways to access elements in an array, `operator[]` is the most commonly used and direct one, just like accessing a regular array. `operator[]` is the subscript operator of container classes, used to **return the element at a specified position**, but without boundary checking. Its usage is completely consistent with ordinary C arrays. `operator[]` provides random access capability in array style, allowing you to quickly access elements at any position. **Word Definition**: `operator[]` is the subscript operator, and the square brackets are the symbol for array access. * * * ## Basic Syntax and Parameters `operator[]` is a member function of container classes. You can use it just like using 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, usually `size_t`) * Description: The position (index) of the element to be accessed. Index starts from 0, and the maximum valid index is `size() - 1`. ### Function Description * **Return Value**: Returns a **reference** to the element at the specified position. If the container is a constant container, it returns a constant reference. * **Effect**: Returns the element at the specified position. No boundary check is performed. Accessing out-of-bounds results in undefined behavior. * **Difference from at()**: `operator[]` does not perform boundary checks, making it slightly faster; `at()` performs boundary checks and throws an exception when out of bounds. * * * ## Example Let's go through a series of examples from simple to complex to fully master the usage of `operator[]`. ### Example 1: Basic Usage - Accessing Elements ## Example #include #include int main(){ // 1. Create an array and initialize it std::array numbers ={10, 20, 30, 40, 50}; std::cout<<"array 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 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:** array size is: 5First element : 10Second element : 20Third element : 30Last element : 50All elements: 10 20 30 40 50 **Code Explanation:** 1. `numbers` returns the first element `10` (index starts from 0). 2. `numbers` returns the last element `50` (since `size()` is 5, valid indices are 0-4). 3. Using loops and `operator[]` allows traversal of all elements, with usage identical to C arrays. ### Example 2: Modifying Element Values `operator[]` returns a reference, so it can be used to modify element values. ## Example #include #include int main(){ std::array numbers ={10, 20, 30}; std::cout<<"Before modification: "; for(size_t i =0; i < numbers.size();++i){ std::cout<< numbers<<" "; } std::cout<< std::endl; // Use operator[] to get a reference and modify elements numbers=100; numbers=200; numbers=300; std::cout<<"After modification: "; for(size_t i =0; i < numbers.size();++i){ std::cout<< numbers<<" "; } std::cout<< std::endl; return 0; } **Expected Output:** Before modification: 10 20 30After modification: 100 200 300 **Code Explanation:** * `numbers = 100;` modifies the value of the first element via reference. * This demonstrates that `operator[]` returns a modifiable lvalue reference. ### Example 3: Range-based For Loop You can use range-based for loops to iterate over an array. ## Example #include #include #include int main(){ std::array names ={"Alice", "Bob", "Charlie"}; std::cout<<"All elements: "; for(const auto& name : names){ std::cout<< name <<" "; } std::cout<< std::endl; return 0; } **Expected Output:** All elements: Alice Bob Charlie **Code Explanation:** * Range-based for loops provide a concise way to access array elements. * Compared to `operator[]`, the code is more concise and readable. ### Example 4: Calculating Vector Dot Product Use `operator[]` to implement vector operations. ## Example #include #include // Calculate the dot product of two vectors int dotProduct(const std::array& v1, const std::array& v2){ int result =0; for(size_t i =0; i < v1.size();++i){ result += v1* v2; } return result; } int main(){ std::array v1 ={1, 2, 3}; std::array 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 Explanation:** * Using `operator[]` allows quick access to array elements in algorithms. * The dot product calculation involves multiplying corresponding elements and summing them up. * * C++ Container Class ](#)
← Cpp Libs Array SwapCpp Libs Array Fill β†’