Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Const vector of non-const objects

In defining a function in an interface :

virtual void ModifyPreComputedCoeffs ( std::vector < IndexCoeffPair_t > & model_ ) = 0; 

we want to specify that the vector model_ should not be altered in the sense push_back etc operations should not be done on the vector, but the IndexCoeffPair_t struct objects in the model_ could be changed. How should we specify that ?

virtual void ModifyPreComputedCoeffs ( const std::vector < IndexCoeffPair_t > & model_ ) = 0; 

does not work I think.

like image 594
Humble Debugger Avatar asked Jul 25 '11 16:07

Humble Debugger


People also ask

Can a const reference be bound to a non const object?

No. A reference is simply an alias for an existing object. const is enforced by the compiler; it simply checks that you don't attempt to modify the object through the reference r .

What is a const vector?

A const vector will return a const reference to its elements via the [] operator . In the first case, you cannot change the value of a const int&. In the second case, you cannot change the value of a reference to a constant pointer, but you can change the value the pointer is pointed to.

Can you push const vector back?

You can't put items into a const vector, the vectors state is the items it holds, and adding items to the vector modifies that state.

Can a const vector be modified?

The reference is to a vector that is const, so its contained type is also considered const. That means you can't directly change the contents of the vector or the contained items.


1 Answers

Rather than passing the vector into the function, do what the standard library does and pass a pair of iterators instead.

virtual void ModifyPreComputedCoeffs ( std::vector < IndexCoeffPair_t >::iterator & model_begin, std::vector < IndexCoeffPair_t >::iterator & model_end ) 
like image 68
Mark Ransom Avatar answered Sep 28 '22 03:09

Mark Ransom