Change data in std::vector inside const context

时间:2019-02-18 00:32:19

标签: c++11 stl

It there a way to change the data stored inside a std::vector inside a const function? See the following code to understand what I want to accomplish:

// class holding properties and data
class Output{
public:
    int * values; // possibility 1: raw pointer
    std::vector<int> vc; // possibility 2: std::vector
    mutable std::vector<int> vm;  // possibility 3: mutable vector
    //std::vector<mutable int> vm; something like this,        
};
class Node{
   Output out;
   void test()const{
       // i want to change the "data" of the Output but not the Object 
       out.values[0] = 0;//works: i can change the output data
       out.values = nullptr;//works: compile error, i cant change the pointer
       out.vc[0] = 1; // compile error, not possible :(
       out.vm[0] = 1; // that is what i want
       out.vm.resize(3); // this is now possible, but should be not possible
   }
};

I can use a raw pointer to achieve my goal, but i would prefer a std::vector if this is possible.

A mutable content vector may looks like this:

template<typename T>
class mutable_vector : public std::vector<T>{
public:
    T& operator[](int index)const{
        return const_cast<mutable_vector<T>*>(this)->data()[index];
    }
    typename std::vector<T>::iterator begin()const{
        return const_cast<mutable_vector<T>*>(this)->begin();
    }
    typename std::vector<T>::iterator rbegin()const{
        return const_cast<mutable_vector<T>*>(this)->rbegin();
    }
};

0 个答案:

没有答案