As an extension to this question Are const_iterators faster?, I have another question on const_iterators
. How to remove constness of a const_iterator
-
You can subtract the begin() iterator from the const_iterator to obtain the position the const_iterator is pointing to and then add begin() back to that to obtain a non-const iterator. I don't think this will be very efficient for non-linear containers, but for linear ones such as vector this will take constant time.
vector<int> v;
v.push_back(0);
v.push_back(1);
v.push_back(2);
v.push_back(3);
vector<int>::const_iterator ci = v.begin() + 2;
cout << *ci << endl;
vector<int>::iterator it = v.begin() + (ci - v.begin());
cout << *it << endl;
*it = 20;
cout << *ci << endl;
EDIT: This appears to only work for linear (random access) containers.
讨论(0)
-
you can convert your const iterator value pointer to a non const value pointer and use it directly something like this
vector<int> v;
v.push_back(0);
v.push_back(1);
v.push_back(2);
v.push_back(2);
vector<int>::const_iterator ci = v.begin() + 2;
cout << *ci << endl;
*const_cast<int*>(&(*ci)) = 7;
cout << *ci << endl;
讨论(0)
-
I believe this conversion is not needed in good designed program.
If you need do this - try redesign code.
As workaround you can do next:
typedef std::vector< size_t > container_type;
container_type v;
// filling container code
container_type::const_iterator ci = v.begin() + 3; // set some value
container_type::iterator i = v.begin();
std::advance( i, std::distance< container_type::const_iterator >( v.begin(), ci ) );
But I'm think that sometimes this conversion is impossible, because your algorithms can haven't access to container.
讨论(0)
- 热议问题