Изменить данные в std :: vector внутри контекста - PullRequest
0 голосов
/ 18 февраля 2019

Есть ли способ изменить данные, хранящиеся внутри std :: vector внутри функции const?Посмотрите следующий код, чтобы понять, чего я хочу достичь:

// 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
   }
};

Я могу использовать необработанный указатель для достижения своей цели, но я бы предпочел std :: vector, если это возможно.

Вектор изменяемого содержимого может выглядеть так:

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();
    }
};
...