Posts

Showing posts with the label const_iterator

How to convert const_iterators to iterators using std::distance and std::advance

Image
A short posting demonstrating how to remove the const-ness of a const_iterator , given that it is not possible to use re-casting along the lines of const_cast to convert from const_iterator to iterator . Consider the following example: [code language="cpp"] #include <iostream> #include <vector> class A { public: A( int x ) { val = x; } void DoStuff() { std::cout << "val = " << val << std::endl; } private: int val; }; int main() { // Initialise vector with pointers to A objects A* a[] = { new A( 1 ), new A( 2 ), new A( 3 ), new A( 4 ) }; std::vector<A*> v( a, a + 4 ); // Iterate over the elements for ( std::vector<A*>::const_iterator cit = v.begin(); cit != v.end(); ++cit ) { std::vector<A*>::iterator it = cit; } return 0; } [/code] Which results in the following compilation error: error C2440: 'initializing' : cannot convert from 'std::_...