Search code examples
c++stlstdstdvector

C++: std::vector [] operator


Why std::vector has 2 operators [] realization?

reference       operator[](size_type pos);
const_reference operator[](size_type pos) const;

Solution

  • One for non-const vector object, and the other for const vector object.

    void f(std::vector<int> & v1, std::vector<int> const & v2)
    {
       //v1 is non-const vector
       //v2 is const vector
    
       auto & x1 = v1[0]; //invokes the non-const version
       auto & x2 = v2[0]; //invokes the const version
    
       v1[0] = 10; //okay : non-const version can modify the object
       v2[0] = 10; //compilation error : const version cannot modify 
    
       x1 = 10; //okay : x1 is inferred to be `int&`
       x2 = 10; //error: x2 is inferred to be `int const&`
    }
    

    As you can see, the non-const version lets you modify the vector element using index, while the const version does NOT let you modify the vector elements. That is the semantic difference between these two versions.

    For more detail explanation, see this FAQ:

    Hope that helps.